Reputation: 173
I have a BigDecimal
262727.00 / 48 = 5473.479166666666667
BigDecimal value = new BigDecimal("5473.479166666666667");
value = value.setScale(0, RoundingMode.HALF_EVEN);
System.out.println(value.toString());
I expect to get 5474 but I got 5473. Has someone idea, how to get the number 5474?
Thank you
Upvotes: 1
Views: 3232
Reputation: 50864
RoundingMode.HALF_EVEN
round towards the "nearest neighbor". .479 is closer to 0 than 1, so it rounds down.
Base on the comments you need to call setScale()
twice, once to get the closest decimal and then the closest number
value = value.setScale(1, RoundingMode.HALF_EVEN).setScale(0, RoundingMode.HALF_EVEN);
Upvotes: 2
Reputation: 701
Not sure what behavior you want for roundinf negative numbers. So, I would say, RoundingMode.CEILING
and RoundingMode.UP
will work in your case.
The difference is only for negative values:
CEILING - Rounding mode to round towards positive infinity.
BigDecimal value = new BigDecimal("-5473.479166666666667");
value = value.setScale(0, RoundingMode.CEILING);
gives -5473
UP - Rounding mode to round away from zero.
BigDecimal value = new BigDecimal("-5473.479166666666667");
value = value.setScale(0, RoundingMode.UP);
gives -5474
Upvotes: 1