Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 1.3 — Decimals: float and Why 0.1 + 0.2 Isn't 0.3
Python · Example 2 of 3

Exact math, infinity and nan

Decimal("0.1") (from text) is exact; Decimal(0.1) (from a float) shows the hidden error.

A float is a number with a decimal point. Computers store floats in binary, so many everyday decimals such as 0.1 cannot be stored exactly and tiny rounding errors appear. Compare floats with math.isclose, and use decimal or fractions when you need exact answers.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Print whether 0.1 + 0.2 equals 0.3, and then whether they are close according to math.isclose.

02

Use Decimal to add the prices 19.99, 5.01 and 0.10 exactly, and print the total.

03

Print round(0.5), round(1.5) and round(2.5) and say why the results are 0, 2 and 2.

Explain it without notes

01

Why does 0.1 + 0.2 == 0.3 return False?

02

How should you compare two floats in Python, and why?

03

What is banker's rounding? What do round(2.5) and round(3.5) return?

04

When would you choose Decimal or Fraction instead of float?

Exact math, infinity and nan
Sign in to run this example in your browser.

Expected output

0.3
True
59.97
0.1000000000000000055511151231257827021181583404541015625
1/2
True
inf -inf True
inf
False True