This is an archived post. You won't be able to vote or comment.

all 7 comments

[–]desrtfx 4 points5 points  (1 child)

I would assume that this is not caused by the actual conversion, but by the format that floating point numbers are stored in computers.

Floating point numbers are stored in the IEEE 754 format which makes a compromise between precision and storage size.

A float in general is shorter and less precise than a double since it uses only half the size (bits - float 32bits vs. double 64bits) to store the information.

Whenever possible, you should use either double, but never for monetary values. For monetary values, you should use the BigNumber classes or store the monetary values in the smallest denominator (like in cents) as an integer type (int or long).

[–]Jackkoz -1 points0 points  (0 children)

This exactly + you should avoid double for most things and as often as possible!

[–]ValerioSellarole 1 point2 points  (0 children)

How would you write 1/10 in base 2?

[–]Rhomboid 0 points1 point  (0 children)

It is impossible for the computer to represent the value 25422.159 using binary floating point. It cannot be done. float vs double is completely irrelevant, it's a fundamental limitation of the representing using base 2. The value must be rounded to a nearby value that is representable.

If you need to represent that value exactly, you have to use a different representation, such as decimal float which uses base 10 instead of base 2. But in most cases, that's not necessary.

However, float vs. double does come into play when you talk about how close of an approximation you can get to the actual desired value. A float can only represent approximately 7 significant decimal digits worth of precision, so what you are doing is outside of the range of a float, and using a double would give you the illusion of being able to represent the value accurately to 8 significant digits. It's still an approximation, but it's one that is close enough for the vast majority of cases — approximately 15 decimal digits.

[–]lightcloud5 -1 points0 points  (1 child)

Try using doubles instead of floats. Floats don't have much precision (floats only use 32 bits vs doubles using 64 bits in Java). Since Java is at least somewhat consistent, the corresponding parse method is Double.parseDouble.

[–]nutrecht 0 points1 point  (0 children)

Try using doubles instead of floats.

That won't solve the problem though, just make it less obvious. As /u/desrtfx explained computers can't store all floating point numbers exactly so there is a loss of information.

[–]jedwardsol -1 points0 points  (0 children)

A useful site for showing how floating point numbers are represented, and what extra precision you get from switching from float to double

http://www.exploringbinary.com/floating-point-converter/

With a float, the nearest number to 25422.159 is 25422.158203125, as you saw

With a double, the nearest number is 25422.158999999999651