Search code examples
javabigdecimal

Round BigDecimal to the nearest integral value


How would I CORRECTLY round a BigDecimal to the nearest whole value?

For instance

1.2 --> 1

1.5 --> 2

1.6 --> 2.

I tried

BigDecimal val = new BigDecimal(1.5);
System.out.println(val.setScale(0, RoundingMode.HALF_UP))

But this still gives me 1. NOT 2 as anticipated.

Does anyone happen to know how to correctly do this?

Thanks


Solution

  •     BigDecimal val = new BigDecimal(1.2);
        System.out.println(val.setScale(0, RoundingMode.HALF_UP));
        val = new BigDecimal(1.5);
        System.out.println(val.setScale(0, RoundingMode.HALF_UP));
        val = new BigDecimal(1.6);
        System.out.println(val.setScale(0, RoundingMode.HALF_UP));
    

    Result:

    1

    2

    2

    I don't see where is the problem