Java BigDecimal setScale和舍入为half_even [英] Java BigDecimal setScale and rounding with half_even
问题描述
我使用带有half_even舍入模式的java BigDecimal setScale方法的以下代码,并得到以下结果。
I am using the following code with the java BigDecimal setScale method with half_even rounding mode and am getting the following results.
new BigDecimal(1.115).setScale(2, RoundingMode.HALF_EVEN).toPlainString()
结果:1.11
预期:1.12
由于距离左边最近的偶数位数应该是2,结果我会期望是1.12。但结果是1.11。再次,
Since the closest even digit to the left to 5 should be 2 the result I would expect is 1.12. But the result is 1.11. And again,
new BigDecimal(1.145).setScale(2, RoundingMode.HALF_EVEN).toPlainString()
结果:1.15
预计:1.14
因为5左边的偶数是4,我希望结果是1.14。对此有何解释?
Because the even digit to the left of 5 is 4 I would expect the result to be 1.14. Any explanation for this?
推荐答案
这是由浮点不精确引起的(在 double
输入中价值)。
This is caused by floating point imprecisions (in your double
input value).
System.out.println(new BigDecimal(1.115));
1.1149999999999999911182158029987476766109466552734375
改为使用String构造函数。
Use the String constructor instead.
BigDecimal.valueOf("1.115")
一旦数字为BigDecimal,就不会丢失精度,并且舍入工作正常。
但是你必须确保数字完整地进入BigDecimal(并且在此之前还没有通过强制它通过浮点类型而丢失精度)。
Once the number is a BigDecimal, no precision is lost and rounding works properly. But you have to make sure the number gets into the BigDecimal intact (and has not already lost precision before that by forcing it through a floating point type).
这篇关于Java BigDecimal setScale和舍入为half_even的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!