Java双精度总结麻烦 [英] Java double precision sum trouble
本文介绍了Java双精度总结麻烦的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
var
(double)2.8
tot.getIva )
(java.lang.Double)0.17
var + tot.get()
(double)2.9699999999999998
我不明白为什么我没有得到简单的2.97!
解决方案
如果你想要 2.97
,你应该使用 BigDecimal
。
double
s被存储为二进制中的分数,而不是十进制。所以 3.75
,例如,只存储为 2 ^ 1 + 2 ^ 0 + 2 ^( - 1)+ 2 ^( - 2)
。
2.8
和 0.17
不能像二进制分数那样精确地表示,所以会有一些舍入误差。
你也可以找到本文有帮助。
I would like to know why I get this error. (this is Display log of Eclipse debug)
var
(double) 2.8
tot.getIva()
(java.lang.Double) 0.17
var+tot.get()
(double) 2.9699999999999998
I can not understand why I did not get simply 2.97!
解决方案
If you wanted 2.97
, you should have used BigDecimal
.
double
s are stored as fractions in binary, not decimal. So 3.75
, for example, is just stored as 2^1 + 2^0 + 2^(-1) + 2^(-2)
.
2.8
and 0.17
cannot be represented exactly as binary fractions, so there's going to be some rounding error.
You may also find this article helpful.
这篇关于Java双精度总结麻烦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文