Double 的 BigDecimal 值不正确?
我正在尝试从字符串创建 BigDecimal。别问我为什么,我就是需要!这是我的代码:
Double theDouble = new Double(".3");
System.out.println("The Double: " + theDouble.toString());
BigDecimal theBigDecimal = new BigDecimal(theDouble);
System.out.println("The Big: " + theBigDecimal.toString());
这是我得到的输出?
The Double: 0.3
The Big: 0.299999999999999988897769753748434595763683319091796875
有什么想法吗?
I am trying to make a BigDecimal from a string. Don't ask me why, I just need it! This is my code:
Double theDouble = new Double(".3");
System.out.println("The Double: " + theDouble.toString());
BigDecimal theBigDecimal = new BigDecimal(theDouble);
System.out.println("The Big: " + theBigDecimal.toString());
This is the output I get?
The Double: 0.3
The Big: 0.299999999999999988897769753748434595763683319091796875
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当您创建双精度型时,无法准确表示值 0.3。您可以从不带中间 double 的字符串创建 BigDecimal,如
浮点数表示为二进制分数和指数。因此,有些数字无法准确表示。在以 10 为基数的数字中也存在类似的问题,例如 1/3,即 0.333333333..... 1/3 的任何十进制表示都是不精确的。这种情况发生在二进制分数的不同集合中,0.3 是二进制中不精确的分数集合之一。
When you create a double, the value 0.3 cannot be represented exactly. You can create a BigDecimal from a string without the intermediate double, as in
A floating point number is represented as a binary fraction and an exponent. Therefore there are some number that cannot be represented exactly. There is an analogous problem in base 10 with numbers like 1/3, which is 0.333333333..... Any decimal representation of 1/3 is inexact. This happens to a DIFFERENT set of fractions in binary, and 0.3 is one of the set that is inexact in binary.
另一种方法是使用
MathContext.DECIMAL32
保证 7 位精度(在我们的例子中已经足够好了):OUTPUT
Another way is to use
MathContext.DECIMAL32
which guarantees 7 digit precision (which is good enough in our case):OUTPUT
由于
new Double(".3")
无法准确表示,因此最接近的值为0x1.3333333333333P-2
或.299999999999999988897769753748434595763683319091796875
,需要的是:这将打印:
Since
new Double(".3")
can't be represented exactly, the nearest value is0x1.3333333333333P-2
or.299999999999999988897769753748434595763683319091796875
, what would be need to is this:This will print:
您可以为大数小数指定指定的精度。例如附加到您的示例:
这将打印出“0.30”
You can give a big decimal a specified precision. e.g. append to your example:
This will print out "0.30"