Java双精度求和麻烦

2022-01-09 00:00:00 floating-point double java

我想知道为什么会出现此错误.(这是Eclipse调试的显示日志)

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

我不明白为什么我没有得到简单的 2.97!

I can not understand why I did not get simply 2.97!

推荐答案

如果你想要 2.97,你应该使用 BigDecimal.

If you wanted 2.97, you should have used BigDecimal.

doubles 在 binary 中存储为分数,而不是十进制.例如,3.75 只是存储为 2^1 + 2^0 + 2^(-1) + 2^(-2).

doubles 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.80.17 不能完全表示为二进制分数,所以会有一些舍入误差.

2.8 and 0.17 cannot be represented exactly as binary fractions, so there's going to be some rounding error.

这篇文章可能对您也有帮助.

相关文章