BigDecimal减法 [英] BigDecimal Subtraction

查看:774
本文介绍了BigDecimal减法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想减去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.

...

注意:


  1. 此构造函数的结果可能有些不可预测。

...

例如:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆