Search code examples
javanumber-formattingbigdecimal

Correct way to format a notation of a number with decimal scale in Java without dividing


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?


Solution

  • 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