Command Palette

Search for a command to run...

Back to the lesson: Topic 1.4 — Decimals: double, float and Why 0.1 + 0.2 Isn't 0.3
Core Java · Example 1 of 3

Rounding errors you can see

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.

01

Add 0.1 ten times. Print the sum, whether it == 1.0, and whether it is within 1e-9 of 1.0.

02

With BigDecimal, compute the total for 3 items at 19.99 plus 18% tax rounded to 2 decimals (HALF_UP).

03

Show that double can't count past 2⁵³: start from 9007199254740992.0, add 1, and print whether the value changed.

Explain it without notes

01

Explain why 0.1 + 0.2 prints 0.30000000000000004 in Java.

02

How should you compare two doubles for equality, and why does a fixed epsilon sometimes fail?

03

What are NaN and Infinity, how do you produce them, and how do you test for them?

04

Why shouldn't you store money in a double, and what should you use instead?

Rounding errors you can see
Sign in to run this example in your browser.

Expected output

0.1 + 0.2       = 0.30000000000000004
equals 0.3?       false
1.03 - 0.42     = 0.6100000000000001
3 * 0.1         = 0.30000000000000004
ten 0.1s        = 0.9999999999999999
close to 1.0?     true
exact 0.1       = 0.1000000000000000055511151231257827021181583404541015625