Ndrik7
Ndrik7

Reputation: 173

How To Rounding BigDecimal with Scale zero

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

Answers (2)

Guy
Guy

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

Suryakant Bharti
Suryakant Bharti

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:

  1. CEILING - Rounding mode to round towards positive infinity.

    BigDecimal value = new BigDecimal("-5473.479166666666667");
    value = value.setScale(0, RoundingMode.CEILING);
    

    gives -5473

  2. UP - Rounding mode to round away from zero.

    BigDecimal value = new BigDecimal("-5473.479166666666667");
    value = value.setScale(0, RoundingMode.UP);
    

    gives -5474

Upvotes: 1

Related Questions