gpt4 book ai didi

java - BigDecimal 错误舍入

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:08:04 25 4
gpt4 key购买 nike

我在使用 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,如您所愿。如果您想要这种舍入,则必须编写一个循环,以逐渐降低精度。

关于java - BigDecimal 错误舍入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33149742/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com