BigDecimal HALF_UP 舍入问题

BigDecimal HALF_UP rounding issue

我正在尝试使用 scale=3 和 HALF_UP 舍入模式对 0.14049 进行舍入,并希望看到舍入值 = 0.141 但得到的是 0.140。

根据我的理解,最后一个十进制数字 9 应该将 4 舍入为 5,并且在使用比例 3 时应该将 0 舍入为 1,我应该看到 0.141。

是 BigDecimal setScale 方法中的错误还是我对舍入的期望是错误的。如何获得类似于 0.141 而不是 0.140 的舍入值?

BigDecimal bd=new BigDecimal("0.14049");
BigDecimal normalizedField = field.setScale(3, RoundingMode.HALF_UP);
System.out.println(normalizedField);
// Output = 0.140

As per my understanding the last decimal digit 9 should round up the 4 to 5 and that should in-turn round up 0 to 1 when using scale 3 and i should see 0.141.

这种理解是不正确的。舍入不是迭代过程。仅考虑刻度位置后的第一个数字,而不是整个数字链。在你的例子中,数字是 4,所以它被转换为零。

根据您的业务领域,“4999998”案例将始终发生在同一位置。我有类似的情况,比例是 2。所以我在四舍五入中添加了额外的步骤。你的情况:

BigDecimal bd=new BigDecimal("0.14049");
BigDecimal normalizedField = bd.setScale(4, RoundingMode.HALF_UP).setScale(3, RoundingMode.HALF_UP);
System.out.println(normalizedField);