BigDecimal减法 [英] BigDecimal Subtraction
问题描述
我想减去2 double
值,我尝试了以下代码。
I want to substract 2 double
values, and I have tried the following code.
double val1 = 2.0;
double val2 = 1.10;
System.out.println(val1 - val2);
我的输出为,
0.8999999999999999
获取输出 0.9
我尝试使用 BigDecimal
,如下所示,
For getting output as 0.9
I tried with BigDecimal
as follows,
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和案例2之间的区别是什么?案例3?
My question is what is the difference between case 2 & case 3?
在案例2中为什么我得到这样的输出?
In case 2 why I got the output like that?
推荐答案
BigDecimal .valueOf(double d)
使用规范 String
表示double值,内部 Double.toString(double使用
,这就是你在第二种情况下获得 0.9
的原因。
BigDecimal.valueOf(double d)
uses canonical String
representation of double value, internally Double.toString(double)
is used, that's why you are getting 0.9
in second case.
注意:这通常是将double(或
float)转换为BigDecimal的首选方法,因为返回的值等于
结果从使用
Double.toString(double)
的结果构造BigDecimal。
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)
.
使用 新BigDecimal(0.9)
它将值转换为精确 floa不使用字符串
表示
$的 double
值的表示表示b $ b
While with new BigDecimal(0.9)
it converts value to exact floating point representation of double
value without using String
representation,
将double转换为
BigDecimal
,这是double的二进制浮点值的精确十进制
表示。
Translates a double into a
BigDecimal
which is the exact decimal representation of the double's binary floating-point value.
...
注意:
- 此构造函数的结果可能有些不可预测。
...
例如:
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
这篇关于BigDecimal减法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!