简体   繁体   中英

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

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM