为什么在Java中浮点数似乎添加不正确? [英] Why do floats seem to add incorrectly in Java?
本文介绍了为什么在Java中浮点数似乎添加不正确?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能的重复项:
JavaScript的数学运算是否被破坏?
Java浮点算法
Possible Duplicates:
Is JavaScript's Math broken?
Java floating point arithmetic
我有当前代码
for(double j = .01; j <= .17; j+=.01){
System.out.println(j);
}
输出为:
0.01
0.02
0.03
0.04
0.05
0.060000000000000005
0.07
0.08
0.09
0.09999999999999999
0.10999999999999999
0.11999999999999998
0.12999999999999998
0.13999999999999999
0.15
0.16
0.17
有人可以解释为什么会这样吗?您如何解决这个问题?除了编写舍入函数以外?
Can someone explain why this is happening? How do you fix this? Besides writing a rounding function?
推荐答案
由于存储方式的不同,浮点数是Java中实际数字的近似值.如果需要精确值,请使用 BigDecimal 代替.
Floats are an approximation of the actual number in Java, due to the way they're stored. If you need exact values, use a BigDecimal instead.
这篇关于为什么在Java中浮点数似乎添加不正确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文