Machado
Machado

Reputation: 14499

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?

Upvotes: 0

Views: 90

Answers (2)

zakinster
zakinster

Reputation: 10698

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

Upvotes: 1

bryce
bryce

Reputation: 852

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.

Upvotes: 0

Related Questions