BigDecimal from double wrong value?

I am trying to make BigDecimal from a string. Do not ask me why, I just need to! 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()); 

Is this the result that I get?

 The Double: 0.3 The Big: 0.299999999999999988897769753748434595763683319091796875 

Any ideas?

+4
source share
3 answers

When you create a double, a value of 0.3 cannot be represented exactly. You can create a BigDecimal from a string without an intermediate double, as in

 new BigDecimal("0.3") 

A floating point number is represented as a binary fraction and exponent. Therefore, there is a certain number that cannot be accurately represented. There is a similar problem in base 10 with numbers like 1/3, which is 0.3333333333 ..... Any decimal representation 1/3 is inaccurate. This happens with a VARIOUS set of fractions in binary format, and 0.3 is one of the set that is inaccurate in binary format.

+12
source

You can give a large decimal digit a given precision. for example add 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 "0.30"

0
source

Another way is to use MathContext.DECIMAL32 , which guarantees the accuracy of 7 digits (which in our case is pretty good):

 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 
0
source

All Articles