BigDecimal from Double incorrect value?

£可爱£侵袭症+ 提交于 2019-11-27 09:44:31

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

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. This happens to a DIFFERENT set of fractions in binary, and 0.3 is one of the set that is inexact in binary.

You can give a big decimal a specified precision. e.g. 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"

Another way is to use MathContext.DECIMAL32 which guarantees 7 digit precision (which is good enough in our case):

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

The Double: 0.3
The Big: 0.3000000
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!