0

I have done a reading about number conversions in Java because I need to format a number inside my Android application.

I'm currently holding a long variable with 4 digits

long variable_1 = 2203;

And this is what I'm looking to print

220.3

What I have done so far

variable_1 = 2203;
BigDecimal bd = new BigDecimal(variable_1);
bd = bd.setScale(1, BigDecimal.ROUND_HALF_UP);

txtView_variable_1.setText(String.valueOf(bd));

Result

2203.0

What am I doing wrong here?

Machado
  • 14,105
  • 13
  • 56
  • 97
  • possible duplicate of [How do I format a number in java?](http://stackoverflow.com/questions/50532/how-do-i-format-a-number-in-java) – StackFlowed Aug 03 '15 at 14:46
  • 5
    try dividing by 10 ? – Havnar Aug 03 '15 at 14:47
  • Simple workaround, but I'm actually looking forward to know why is it not converting to `220.3`. – Machado Aug 03 '15 at 14:48
  • 1
    Because 220.3 is not the scientific notation for 2203? – Yuri Aug 03 '15 at 14:49
  • Is it possible to move the notation instead of dividing by 10? – Machado Aug 03 '15 at 14:51
  • How do you determine the number of digits that will go after the decimal point? – Zaid Malhis Aug 03 '15 at 14:53
  • `bd.setScale(1, BigDecimal.ROUND_HALF_UP);` where 1 is the the `newScale` i.e. number of digits. I know it looks kind of silly, but dividing is *not* the best approach here. – Machado Aug 03 '15 at 14:54
  • 1
    @Holmes changing the scale will return a new `BigDecimal` with the specified scale but with the same numerical value. It won't change the interpretation of the unscaled number. The underlying scaled number will be rescaled. See my answer for a way to correctly interpret an unscaled number. – zakinster Aug 03 '15 at 15:10

2 Answers2

1

If you change the scale of a BigDecimal, it will return a new BigDecimal with the specified scale but with the same numerical value. It won't change the interpretation of the unscaled number. The underlying scaled number will be rescaled.

You should give the scale at the initialization of the BigDecimal in order for it to interpret correctly your unscaled number :

long variable_1 = 2203;
BigDecimal bd = new BigDecimal(BigInteger.valueOf(variable_1), 1);
System.out.println(String.valueOf(bd));

Which outputs :

220.3
zakinster
  • 10,508
  • 1
  • 41
  • 52
0

I had the same problem to round at 0.1 I managed it like this:

  private BigDecimal roundBigDecimal(BigDecimal valueToRound) {
    int valeurEntiere = valueToRound.intValue();
    String str = String.valueOf(valeurEntiere);
    int rounding = valeurEntiere == 0 ? 1 : str.length() + 1;
    return new BigDecimal(String.valueOf(valueToRound), new MathContext(rounding, RoundingMode.HALF_UP));
  }

In fact the int rounding depends of the number of digit of the number.

bryce
  • 842
  • 11
  • 35