使用HALF_UP舍入到最接近的值

时间:2019-01-08 07:23:34

标签: java rounding bigdecimal

我想将BigDecimal值舍入到最接近的整数。

我尝试使用此问题Java BigDecimal: Round to the nearest whole value的解决方案,但这对我不起作用。

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

在以下情况下可以正常使用

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

但是失败了

    100.47 -> 100 instead of 101.

为什么此代码不起作用?

1 个答案:

答案 0 :(得分:5)

您希望始终将数字四舍五入,在这种情况下,请使用RoundingMode。UP

HALF_UP仅从.5起向上舍入

  

除非两个邻居都等距,否则舍入模式将朝“最近的邻居”舍入。

表显示了这些舍入运算的结果:

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