Difficulties with rounding using Bigdecimal

Asked

Viewed 5,228 times

1

I wrote the following method:

public static double round(double value, int scale) {
    BigDecimal bd = new BigDecimal(value);
    bd.setScale(scale, BigDecimal.ROUND_HALF_UP);
    return bd.doubleValue();
}

I make the call:

round(72.46976811594203, 2)

And get the following output:

72.46976811594203

I would like it to be returned 72.47 as I am rounding to two decimal places. Where is the error?

1 answer

7


Bigdecimal is immutable, so when you call the method setScale() it does not change the variable value bd, he returns the rounded value, however as there is no variable receiving the return value it is simply thrown to the wind, ie the rounded value is never used.

A possible solution is thus:

public static void main(String[] args) {
    System.out.println(round(72.46976811594203, 2));
}
public static double round(double value, int scale) {
    BigDecimal bd1 = new BigDecimal(value);
    BigDecimal bd2 = bd1.setScale(scale, BigDecimal.ROUND_HALF_UP);
    return bd2.doubleValue();
}

Prints:

72.47

Note that the value returned by setScale() is stored in a new variable, and the value of that variable is then returned by the method round().

Reference: Bigdecimal - Java SE 7

  • I really made a big mistake. I didn’t notice that setScale() returned the result. Thankful!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.