Python traps · Python

Python can't add 0.1 + 0.2?FREE

Watch the video

0.1 has no exact binary form, so 0.1 + 0.2 isn't 0.3. Two fixes: math.isclose() and Decimal.

# 0.1 + 0.2 = 0.30000000000000004 ?!
# 0.1 has no exact binary form (like 1/3 in decimal), so a tiny error shows up.
import math

print(0.1 + 0.2)              # 0.30000000000000004 ?!
print(0.1 + 0.2 == 0.3)       # False ?!

# Fix 1: compare with a tolerance
print(math.isclose(0.1 + 0.2, 0.3))   # True ✓

# Fix 2: money? use Decimal from strings
from decimal import Decimal
print(Decimal("0.1") + Decimal("0.2"))  # 0.3 ✓
Open code P2 in Pocket Compiler Download the Pocket Compiler app — free

No app yet? Install it, then open the app and type the code P2 in Code Library.