| Author |
converting float to double
|
Jon Wynett
Greenhorn
Joined: Jun 28, 2004
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
Joined: Jul 11, 2003
Posts: 1392
|
|
Hi Jon, How about this? Joyce
|
 |
marc weber
Sheriff
Joined: Aug 31, 2004
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 For details on IEEE 754, follow the links here... http://www.public.iastate.edu/~sarita/ieee754/homepage.html [ October 04, 2004: Message edited by: marc weber ]
|
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
|
 |
Ilja Preuss
author
Sheriff
Joined: Jul 11, 2001
Posts: 14112
|
|
|
With other words, you can't really store the value 18.4 in a float, because in binary doesn't have a finite number of decimal places (similar to 0.1 ternary = 1*3^(-1) = 1/3 doesn't have a finite number of decimal places in the decimal system). What gets stored is a close approximation.
|
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
|
 |
 |
|
|
subject: converting float to double
|
|
|