简体   繁体   English

Double 中的 BigDecimal 值不正确?

[英]BigDecimal from Double incorrect value?

I am trying to make a BigDecimal from a string.我正在尝试从字符串中创建一个 BigDecimal。 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?这是我得到的output?

The Double: 0.3
The Big: 0.299999999999999988897769753748434595763683319091796875

Any ideas?有任何想法吗?

When you create a double, the value 0.3 cannot be represented exactly. 创建double时,无法准确表示值0.3。 You can create a BigDecimal from a string without the intermediate double, as in 您可以从没有中间双精度的字符串创建BigDecimal,如

new BigDecimal("0.3")

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. 在基数10中存在类似的问题,其数字如1/3,即0.333333333 .....任何1/3的十进制表示都是不精确的。 This happens to a DIFFERENT set of fractions in binary, and 0.3 is one of the set that is inexact in binary. 这发生在二进制的一组不同分数中,而0.3是二进制中不精确的集合之一。

Since new Double(".3") can't be represented exactly, the nearest value is 0x1.3333333333333P-2 or .299999999999999988897769753748434595763683319091796875 , what would be need to is this:由于new Double(".3")不能准确表示,最接近的值是0x1.3333333333333P-2.299999999999999988897769753748434595763683319091796875 ,需要的是:

Double theDouble = new Double(".3");
System.out.println("The Double: " + theDouble.toString());
BigDecimal theBigDecimal = new 
BigDecimal(theDouble).setScale(2, RoundingMode.CEILING);  // <-- here
System.out.println("The Big: " + theBigDecimal.toString());

This will print:这将打印:

The Double: 0.3
The Big: 0.30

You can give a big decimal a specified precision. 您可以给指定精度的大小数。 eg append to your example: 例如附加到你的例子:

Double theDouble = new Double(".3");
theBigDecimal = new BigDecimal(theDouble, new MathContext(2));
System.out.println("The Big: " + theBigDecimal.toString());

This will print out "0.30" 这将打印出“0.30”

Another way is to use MathContext.DECIMAL32 which guarantees 7 digit precision (which is good enough in our case): 另一种方法是使用MathContext.DECIMAL32 ,它保证7位数的精度(在我们的例子中足够好):

Double theDouble = new Double(".3");
System.out.println("The Double: " + theDouble.toString());
BigDecimal theBigDecimal = new BigDecimal(theDouble, MathContext.DECIMAL32);  // <-- here
System.out.println("The Big: " + theBigDecimal.toString());

OUTPUT OUTPUT

The Double: 0.3
The Big: 0.3000000

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM