• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Devaka Cooray
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Martijn Verburg
  • Frits Walraven
  • Himai Minh

problems with float and double

 
Ranch Hand
Posts: 128
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


 
Saloon Keeper
Posts: 14501
325
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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".
 
reply
    Bookmark Topic Watch Topic
  • New Topic