2

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?

Ori Marko
  • 56,308
  • 23
  • 131
  • 233
I. Petrov
  • 63
  • 1
  • 5
  • 9
    `100.47 -> 100` seems totally fine to me. – Dang Nguyen Jan 08 '19 at 07:29
  • Why do you expect 100.47 to round to 101? – Klitos Kyriacou Jan 08 '19 at 07:33
  • **`RoundingMode.HALF_UP` does not round 100.47 to 100.5 and then round again to 101.00**. Instead, it just takes the first decimal place and rounds based on that. Thus, 100.47 gets correctly rounded to 100.00. – deHaar Jan 08 '19 at 07:36
  • 1
    Thank you, everyone. I understand my problem. I need mathematical rounding for my case. – I. Petrov Jan 08 '19 at 07:44
  • Looks like a duplicate of the previous question: https://stackoverflow.com/questions/54059564/bigdecimal-rounding-modes. There it is 35.64999 that doesn't round up. The answer would be the same too. – Rudy Velthuis Jan 08 '19 at 10:59
  • Do what I propose in the duplicate (https://stackoverflow.com/questions/54059564/bigdecimal-rounding-modes): round to 1 decimal first (which does 100.47 --> 100.5) and then to 0 decimals (100.5 --> 101.00). That is not "mathematical rounding" though, that is just what is taught in some schools, i.e. that 1.444445 rounds to 1.44445 and then to 1.4445, 1.445, 1.45, 1.5 and finally to 2. But that is wrong. Anything below 1.500000 should round down. Mathematical rounding (5, 6, 7, 8, 9 are rounded up) **only counts for 1 digit** not for the sequence above. – Rudy Velthuis Jan 08 '19 at 11:01

1 Answers1

5

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
Ori Marko
  • 56,308
  • 23
  • 131
  • 233
  • 1
    Not sure why this was accepted. That would round all the numbers (100.xy) in the question to 101, and that doesn't seem to be what the question asks for. – Rudy Velthuis Jan 08 '19 at 11:41