This week's book giveaways are in the Refactoring and Agile forums.We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!

# converting float to double

Jon Wynett
Greenhorn
Posts: 10
How can I convert a float to a double without have the number "adjusted". For example, if I create a Float with value 18.4 and then either get the doubleValue() or create a new Double with that Float, it comes out as 18.399999618530273.

I've tried this with many different numbers and all get the same type of problem. Also, casting a float as a double gets the same problem.

Here's some sample code:
public static void testFloatToDouble() {
Float f = new Float(18.4);
Double d = new Double(f.floatValue());
System.out.println("Float: " + f);
System.out.println("Float as double: " + f.doubleValue());
System.out.println("Float as Double: " + d);
}
And the results:
Float: 18.4
Float as double: 18.399999618530273
Float as Double: 18.399999618530273

Jon

Joyce Lee
Ranch Hand
Posts: 1392
Hi Jon,

Joyce

marc weber
Sheriff
Posts: 11343
This is a consequence of the way floating-point numbers are stored in computers (per IEEE 754 standards). If the decimal portion cannot be expressed as a sum of reciprocal powers of 2 within a particular "window," then the number loses precision.

If you want precision, then you should use the BigDecimal class in java.math. But be sure to use the String constructor, or you'll get similar errors. Compare the String and double constructor descriptions in the API...

http://java.sun.com/j2se/1.4.2/docs/api/java/math/BigDecimal.html