我想减去 2 个 double
值,我试过下面的代码。
double val1 = 2.0;
double val2 = 1.10;
System.out.println(val1 - val2);
我得到的输出是,
0.8999999999999999
为了获得 0.9
的输出,我尝试使用 BigDecimal
如下,
BigDecimal val1BD = new BigDecimal(val1);
BigDecimal val2BD = new BigDecimal(val2);
System.out.println(val1BD.subtract(val2BD));
我得到的输出是,
0.899999999999999911182158029987476766109466552734375
然后我尝试使用 BigDecimal.valueOf()
val1BD = BigDecimal.valueOf(val1);
val2BD = BigDecimal.valueOf(val2);
System.out.println(val1BD.subtract(val2BD));
最后我得到了 0.9
的输出。
我的问题是案例 2 和案例 3 之间有什么区别?
在情况 2 中,为什么我得到这样的输出?
最佳答案
BigDecimal.valueOf(double d)
使用 double 值的规范 String
表示,在内部使用 Double.toString(double)
,这就是为什么您在第二种情况下得到 0.9
的原因。
Note: This is generally the preferred way to convert a double (or float) into a BigDecimal, as the value returned is equal to that resulting from constructing a BigDecimal from the result of using
Double.toString(double)
.
同时使用 new BigDecimal(0.9)
它将值转换为 double
值的精确 float 表示,而不使用 String
表示,
Translates a double into a
BigDecimal
which is the exact decimal representation of the double's binary floating-point value....
NOTES :
- The results of this constructor can be somewhat unpredictable.
...
例如:
BigDecimal bd1 = new BigDecimal(Double.toString(0.9));
BigDecimal bd2 = new BigDecimal(0.9);
System.out.println(bd1);
System.out.println(bd2);
输出:
0.9
0.90000000000000002220446049250313080847263336181640625
关于java - 大数减法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32546553/