Stephan van Hulst

Saloon Keeper

Posts: 7991

143

posted 2 years ago

Doubles and floats don't have infinite precision. If I ask you to write down 1/3 as a decimal, you would ask me how many digits you should write down, because you can't write it down infinitely precise.

Like 1/3 in decimal, there are some numbers that can't be written in binary with infinite precision. Apparently, 5.8, 5.6 and/or 11.4 are such numbers.

As for why 0.00 is represented as "0.0" and not "0.00", it's because floats and doubles don't store information about their precision. They always have 32 and 64 bits of precision respectively. 0.0 and 0.00 are the same value, so have the same String representation when you use the same precision.

Floating point numbers that represent an exact integer (in this case 0) are printed with an additional ".0", just to make it obvious they are floating point numbers.

If you want a data type that stores precision along with the value, you should use BigDecimal. BigDecimal "0.0" is not equal to BigDecimal "0.00".

Like 1/3 in decimal, there are some numbers that can't be written in binary with infinite precision. Apparently, 5.8, 5.6 and/or 11.4 are such numbers.

As for why 0.00 is represented as "0.0" and not "0.00", it's because floats and doubles don't store information about their precision. They always have 32 and 64 bits of precision respectively. 0.0 and 0.00 are the same value, so have the same String representation when you use the same precision.

Floating point numbers that represent an exact integer (in this case 0) are printed with an additional ".0", just to make it obvious they are floating point numbers.

If you want a data type that stores precision along with the value, you should use BigDecimal. BigDecimal "0.0" is not equal to BigDecimal "0.00".

*The mind is a strange and wonderful thing. I'm not sure that it will ever be able to figure itself out, everything else, maybe. From the atom to the universe, everything, except itself.*