• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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

 
Sheriff
Posts: 5555
326
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: 79153
377
  • 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.
[edit]Corrected compile‑time error in that code.
reply
    Bookmark Topic Watch Topic
  • New Topic