← Back to Python, page 2

python-0033 · Easy fresher

Why does 0.1 + 0.2 == 0.3 evaluate to False, and how should money be handled?

Floats are binary fractions, and 0.1 and 0.2 cannot be represented exactly, so their sum is 0.30000000000000004. Compare floats with math.isclose, and use decimal.Decimal (built from strings) or integer paise for money. round() uses banker's rounding on exact halves.

Full answer
python
import math
from decimal import Decimal, ROUND_HALF_UP
print(0.1 + 0.2, 0.1 + 0.2 == 0.3, math.isclose(0.1 + 0.2, 0.3))
print(Decimal("0.1") + Decimal("0.2"), Decimal(0.1))
print(round(2.5), round(3.5), round(2.675, 2))
print(Decimal("2.675").quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))
price_paise = 4550
print(price_paise * 3 / 100)

Output:

text
0.30000000000000004 False True
0.3 0.1000000000000000055511151231257827021181583404541015625
2 4 2.67
2.68
136.5

Decimal('0.1') is exact, while Decimal(0.1) reveals the float's real binary value, which is why Decimals should be built from strings. round(2.5) gives 2 and round(3.5) gives 4: Python rounds exact halves to the even neighbour. round(2.675, 2) gives 2.67 because the float is slightly below 2.675. For invoices, use Decimal with an explicit rounding mode or keep amounts in integer paise and format only for display.

python
import math
from decimal import Decimal, ROUND_HALF_UP
print(0.1 + 0.2, 0.1 + 0.2 == 0.3, math.isclose(0.1 + 0.2, 0.3))
print(Decimal("0.1") + Decimal("0.2"), Decimal(0.1))
print(round(2.5), round(3.5), round(2.675, 2))
print(Decimal("2.675").quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))
price_paise = 4550
print(price_paise * 3 / 100)

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Floats are binary approximations
  • Use math.isclose to compare
  • Build Decimal from strings
  • round uses banker's rounding
  • Store money as Decimal or integer minor units

Common mistakes

  • Comparing floats with ==
  • Constructing Decimal from a float

Follow-ups

  • What is the decimal context?
  • How does rounding work for negative numbers?

Tips

  • Show the exact sum