A shop bill: float, Decimal and whole paise
1000 items at 0.10 each. The float total is off, Decimal and whole paise are exact. The last lines show why round(2.675, 2) gives 2.67 while Decimal gives 2.68, and why isclose needs abs_tol near zero.
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.
Print whether 0.1 + 0.2 equals 0.3, and then whether they are close according to math.isclose.
Use Decimal to add the prices 19.99, 5.01 and 0.10 exactly, and print the total.
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
Why does 0.1 + 0.2 == 0.3 return False?
How should you compare two floats in Python, and why?
What is banker's rounding? What do round(2.5) and round(3.5) return?
When would you choose Decimal or Fraction instead of float?
Expected output
99.9999999999986 False True
100.00 True
100 0
3.60 23.59
2.67 2.68 0.12
False True