Difficulties with rounding using BigDecimal

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 I get the following output:

  

72.46976811594203

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

    
asked by anonymous 14.10.2014 / 20:21

1 answer

7

BigDecimal is immutable, so when you call the setScale() method it does not change the value of the bd variable, it returns the rounded value, however since there is no variable getting the value of return it is simply thrown in the wind, ie the rounded value is never used.

One possible solution is as follows:

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

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

Reference: BigDecimal - Java SE 7

    
14.10.2014 / 21:01