new BigDecimal(double)vs new BigDecimal(String) [英] new BigDecimal(double) vs new BigDecimal(String)

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

问题描述

BigDecimal double BigDecimal 输入字符串似乎出现了不同的结果。

When BigDecimal is used with an input of double and BigDecimal with an input of String different results seem to appear.

BigDecimal a = new BigDecimal(0.333333333);
BigDecimal b = new BigDecimal(0.666666666);

BigDecimal c = new BigDecimal("0.333333333");
BigDecimal d = new BigDecimal("0.666666666");

BigDecimal x = a.multiply(b);
BigDecimal y = c.multiply(d);

System.out.println(x);
System.out.println(y);

x输出为

0.222222221777777790569747304508155316795087227497352441864147715340493949298661391367204487323760986328125

,而y

0.222222221777777778

我说错了是因为双重不精确?但由于这是一个 BigDecimal ,它不应该是一样的吗?

Am I wrong in saying that this is because of double imprecision? But since this is a BigDecimal, shouldn't it be the same?

推荐答案


我说错误是因为双重不精确?

Am I wrong in saying that this is because of double imprecision?

你是完全正确的,这正是因为 double 的不精确。

You are absolutely right, this is exactly because of double's imprecision.


但由于这是 BigDecimal ,不应该是一样的吗?

But since this is a BigDecimal, shouldn't it be the same?

不,它不应该。您创建 new BigDecimal(0.333333333)时会引入错误,因为 0.333333333 常量已嵌入错误。那时你无法解决这个表征错误:到那时众所周知的马已经离开了谷仓,所以关闭门已经太迟了。

No, it shouldn't. The error is introduced the moment you create new BigDecimal(0.333333333), because 0.333333333 constant already has an error embedded in it. At that point there is nothing you can do to fix this representation error: the proverbial horse is out of the barn by then, so it's too late to close the doors.

另一方面,当您传递 String 时,十进制表示与字符串完全匹配,因此您得到的结果不同。

When you pass a String, on the other hand, the decimal representation matches the string exactly, so you get a different result.

这篇关于new BigDecimal(double)vs new BigDecimal(String)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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