Java BigDecimal精度问题 [英] Java BigDecimal precision problems
本文介绍了Java BigDecimal精度问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道以下行为是一个老问题,但我仍然不明白。
I know the following behavior is an old problem, but still I don't understand.
System.out.println(0.1 + 0.1 + 0.1);
或者即使我使用 BigDecimal
System.out.println(new BigDecimal(0.1).doubleValue()
+ new BigDecimal(0.1).doubleValue()
+ new BigDecimal(0.1).doubleValue());
为什么这个结果是: 0.30000000000000004
而不是: 0.3
?
Why this result is: 0.30000000000000004
instead of: 0.3
?
我该如何解决这个问题?
How can I solve this?
推荐答案
你真正想要的是
new BigDecimal("0.1")
.add(new BigDecimal("0.1"))
.add(new BigDecimal("0.1"));
新的BigDecimal(双)
构造函数获取 double
的所有不精确,所以当你说 0.1
时,你已经引入了舍入错误。使用 String
构造函数可以避免与通过 double
进行相关的舍入错误。
The new BigDecimal(double)
constructor gets all the imprecision of the double
, so by the time you've said 0.1
, you've already introduced the rounding error. Using the String
constructor avoids the rounding error associated with going via the double
.
这篇关于Java BigDecimal精度问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文