• Post Reply Bookmark Topic Watch Topic
  • New Topic

problems with float and double  RSS feed

 
John Losty
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


 
Stephan van Hulst
Saloon Keeper
Posts: 7991
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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".
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!