返回奇怪结果的 BigDecimal setScale 方法
BigDecimal setScale method returning strange results
我有一个区域正在执行以下操作:
BigDecimal number = new BigDecimal(String.valueOf("81.4125"));
上面是一个小数位数设置为4的BigDecimal;
但是如果我执行以下操作:
BigDecimal roundedNumber = number.setScale(2, RoundingMode.HALF_UP);
它 returns 81.41 这显然是不正确的。如果我运行同样用404.1675实验,那就returns404.17!!这是预期的还是为 BigDecimal 类?
记录的某种行为
韩国,
我认为这实际上是使用 2 的比例和 RoundingMode HALF_UP 的正确舍入。
BigDecimal 的 Javadocs 定义 ROUND_HALF_UP 来执行以下操作:
Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up. Behaves as for ROUND_UP if the discarded fraction is ≥ 0.5; otherwise, behaves as for ROUND_DOWN. Note that this is the rounding mode that most of us were taught in grade school.
所以这些测试用例看起来符合规范。
由于小数位数设置为 2,您的十进制数将有两位数,因此它会查看第三位数字来确定四舍五入的方式。希望这对您有所帮助!
我有一个区域正在执行以下操作:
BigDecimal number = new BigDecimal(String.valueOf("81.4125"));
上面是一个小数位数设置为4的BigDecimal;
但是如果我执行以下操作:
BigDecimal roundedNumber = number.setScale(2, RoundingMode.HALF_UP);
它 returns 81.41 这显然是不正确的。如果我运行同样用404.1675实验,那就returns404.17!!这是预期的还是为 BigDecimal 类?
记录的某种行为韩国,
我认为这实际上是使用 2 的比例和 RoundingMode HALF_UP 的正确舍入。
BigDecimal 的 Javadocs 定义 ROUND_HALF_UP 来执行以下操作:
Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up. Behaves as for ROUND_UP if the discarded fraction is ≥ 0.5; otherwise, behaves as for ROUND_DOWN. Note that this is the rounding mode that most of us were taught in grade school.
所以这些测试用例看起来符合规范。
由于小数位数设置为 2,您的十进制数将有两位数,因此它会查看第三位数字来确定四舍五入的方式。希望这对您有所帮助!