Search code examples
javaroundingbigdecimal

Round to nearest value using HALF_UP


I want to round BigDecimal value to the nearest integer.

I tried to used solution from this issue Java BigDecimal: Round to the nearest whole value , but it doesn't work for me.

BigDecimal scaled = value.setScale(0, RoundingMode.HALF_UP);
System.out.println(value + " -> " + scaled);

It works right in case such:

100.12 -> 100.00
100.44 -> 100.00
100.50 -> 101.00
100.75 -> 101.00

But it failed in case

    100.47 -> 100 instead of 101.

Why this code doesn't work?


Solution

  • You expect to round up the number always, in your case use RoundingMode.UP

    HALF_UP will round only from .5 up

    Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up.

    Table showing the results of these rounding operations:

    Input Number  UP  DOWN    CEILING FLOOR   HALF_UP HALF_DOWN   HALF_EVEN   UNNECESSARY
    5.5           6     5      6       5       6          5         6   throw ArithmeticException
    2.5           3     2      3       2       3          2         2   throw ArithmeticException
    1.6           2     1      2       1       2          2         2   throw ArithmeticException
    1.1           2     1      2       1       1          1         1   throw ArithmeticException