Numeric & money bugs

Why 0.1 + 0.2 doesn't equal 0.3, and why odometers roll over to 0.

The idea

Computers represent decimals using Floating Point math (IEEE 754), which uses binary fractions. Just like 1/3 cannot be written perfectly in base-10 (0.3333...), 0.1 cannot be written perfectly in base-2. It is an approximation. If you use floats for money, those tiny rounding errors accumulate, and money goes missing.

Computers also use fixed-size boxes (like 8-bits) for integers. The maximum value an 8-bit signed integer can hold is 127. If you add 1 to 127, the binary digits flip completely over, resulting in -128 (Integer Overflow).

1. Floating Point Money Bug
0.1 + 0.2 (Float64) = 0.30000000000000004
10 + 20 (Integer Cents) = 30 cents
2. 8-Bit Integer Overflow (Signed)
01111110
Decimal: 126
Click Add +1 to approach the maximum limit of an 8-bit signed integer (127).

How it works (Handling Money)

# BAD: Floating point for currency
price = 0.10
tax = 0.20
total = price + tax
print(total) # 0.30000000000000004

# GOOD: Use Integers (Cents)
# Store everything as the smallest indivisible unit
price_cents = 10
tax_cents = 20
total_cents = price_cents + tax_cents
print(f"${total_cents / 100:.2f}") # $0.30

# GOOD: Use Decimal Types
from decimal import Decimal
total = Decimal('0.10') + Decimal('0.20') # 0.30