问题描述
我的同事做了这个实验:
My coworker did this experiment:
public class DoubleDemo {
public static void main(String[] args) {
double a = 1.435;
double b = 1.43;
double c = a - b;
System.out.println(c);
}
}
对于这个一级操作,我预计这个输出:
For this first-grade operation I expected this output:
0.005
但意外的是输出是:
0.0050000000000001155
为什么在这样简单的操作中双重失败?如果double不是这个工作的数据类型,我该怎么用?
Why does double fails in such a simple operation? And if double is not the datatype for this work, what should I use?
推荐答案
double
内部存储为二进制中的分数,例如
1/4 + 1/8 + 1/16 + ...
价值
0.005
- 或价值 1.435
- 不能以二进制存储为精确分数,因此 double
无法存储确切值 0.005
,而
The value
0.005
-- or the value 1.435
-- cannot be stored as an exact fraction in binary, so double
cannot store the exact value 0.005
, and the subtracted value isn't quite exact.
如果您关心精确的十进制算术,请使用
BigDecimal
。
If you care about precise decimal arithmetic, use
BigDecimal
.
您还可以找到有用阅读。
You may also find this article useful reading.
这篇关于双减精度问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!