BigDecimal 错误舍入
BigDecimal wrong rounding
我在使用 BigDecimal 的小数位数和 RoundingMode 对数字进行舍入时遇到问题。
这是我的一段代码:
BigDecimal taxAmount = new BigDecimal("0.8445");
taxAmount = taxAmountPrecision.setScale(2, RoundingMode.HALF_UP);
如果我输入 0.845,它四舍五入得很好,但如果有 0.8445,则 taxAmount 为 0.84。
应该是 0.8445 -> 0.845 -> 0.85。
这正是该舍入方法的 expected behavior。
Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up.
0.8445 到小数点后 2 位的最近邻是 0.84。 HALF_UP
如果值为 0.845 或更大(值的中间值),则舍入为 0.85,如果小于该值,则舍入为 0.844。 0.8445小于0.845,所以向下舍入。
没有中间舍入步骤来传播 5
,如您所愿。如果你想要那种舍入,你将不得不编写一个循环来逐渐降低精度。
为了实现所需的行为,您必须先将比例设置为 3,然后再设置为 2:
BigDecimal taxAmount = new BigDecimal("0.8445");
taxAmount = taxAmount.setScale(3, RoundingMode.HALF_UP).setScale(2, RoundingMode.HALF_UP);
根据要求(例如您应该期望的小数位数),在循环中执行递减精度逻辑更有意义。
我在使用 BigDecimal 的小数位数和 RoundingMode 对数字进行舍入时遇到问题。
这是我的一段代码:
BigDecimal taxAmount = new BigDecimal("0.8445");
taxAmount = taxAmountPrecision.setScale(2, RoundingMode.HALF_UP);
如果我输入 0.845,它四舍五入得很好,但如果有 0.8445,则 taxAmount 为 0.84。
应该是 0.8445 -> 0.845 -> 0.85。
这正是该舍入方法的 expected behavior。
Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up.
0.8445 到小数点后 2 位的最近邻是 0.84。 HALF_UP
如果值为 0.845 或更大(值的中间值),则舍入为 0.85,如果小于该值,则舍入为 0.844。 0.8445小于0.845,所以向下舍入。
没有中间舍入步骤来传播 5
,如您所愿。如果你想要那种舍入,你将不得不编写一个循环来逐渐降低精度。
为了实现所需的行为,您必须先将比例设置为 3,然后再设置为 2:
BigDecimal taxAmount = new BigDecimal("0.8445");
taxAmount = taxAmount.setScale(3, RoundingMode.HALF_UP).setScale(2, RoundingMode.HALF_UP);
根据要求(例如您应该期望的小数位数),在循环中执行递减精度逻辑更有意义。