• 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
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

Java Puzzlers - Puzzle 2: Time for a Change (double arithmetic)

 
Marshal
Posts: 5316
324
IntelliJ IDE Python Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The puzzle asks the reader what is printed by the following code snippet:

You would think it would print 0.90 right? Wrong.

Apparently the value 1.1 cannot be represented exactly as a double so it is represented as the closest double value. Then when subtracted from 2.0, the result is not the closest double to 0.9, so you get 0.8999999999999999.

This is something I found surprising, and I've learnt something new about the double type.

It goes on to discuss that for this very reason you should not ever use a floating point type to represent monetary values, which I did know but not precisely why, and summarises:

Java Puzzlers wrote:In summary, avoid float and double where exact answers are required; for monetary calculations, use int, long, or BigDecimal.


These puzzles are quite fun aren't they? Right, what's next....
 
Marshal
Posts: 75615
354
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
That is why 0.1D is very slightly larger than 0.1 and if you try a loop it runs 11 timesI wrote about BigDecimal here and here.
 
I knew I would regret that burrito. But this tiny ad has never caused regrets:
free, earth-friendly heat - a kickstarter for putting coin in your pocket while saving the earth
https://coderanch.com/t/751654/free-earth-friendly-heat-kickstarter
reply
    Bookmark Topic Watch Topic
  • New Topic