views:

45

answers:

2

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?

+4  A: 

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.

Jim Garrison
Why cant it be represented exactly as a double?
Diego
@Diego: This is, if not the most common question on SO, at least in the top five. It takes a little time to understand, though. Read [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://docs.sun.com/source/806-3568/ncg_goldberg.html)
Michael Petrotta
@Michael Petrotta ok thanks!
Diego
A: 

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"

Steve B.
Thanks, but I dont always know that the precision would be. The string I am actually reading from a file.
Diego