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....