Infinity, NaN and other special values
double and float store numbers in binary scientific notation with a fixed number of digits, so most decimal fractions like 0.1 are stored as the nearest binary approximation. That's why 0.1 + 0.2 prints 0.30000000000000004, why you never compare decimals with ==, and why money belongs in BigDecimal.
Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Add 0.1 ten times. Print the sum, whether it == 1.0, and whether it is within 1e-9 of 1.0.
With BigDecimal, compute the total for 3 items at 19.99 plus 18% tax rounded to 2 decimals (HALF_UP).
Show that double can't count past 2⁵³: start from 9007199254740992.0, add 1, and print whether the value changed.
Explain it without notes
Explain why 0.1 + 0.2 prints 0.30000000000000004 in Java.
How should you compare two doubles for equality, and why does a fixed epsilon sometimes fail?
What are NaN and Infinity, how do you produce them, and how do you test for them?
Why shouldn't you store money in a double, and what should you use instead?
Expected output
1.0 / 0 = Infinity
-1.0 / 0 = -Infinity
0.0 / 0 = NaN
NaN == NaN : false
isNaN : true
inf - inf = NaN
sqrt(-1) = NaN
-0.0 == 0.0 : true
1 / -0.0 = -Infinity
MIN_VALUE = 4.9E-324
float 2^24 + 1 = 1.6777216E7