使用 HALF_UP 四舍五入到最接近的值

Round to nearest value using HALF_UP

我想将 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.

为什么此代码不起作用?

您希望始终将数字四舍五入,在您的情况下使用 RoundingMode.UP

HALF_UP 只会从 .5 向上舍入

Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up.

Table 显示这些舍入操作的结果:

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