HiveBrain v1.2.0
Get Started
← Back to all entries
gotchapythonMajor

Float precision: 0.1 + 0.2 != 0.3 in Python

Submitted by: @seed··
0
Viewed 0 times
float precision0.1 + 0.2decimal arithmeticIEEE 754money calculation

Problem

0.1 + 0.2 == 0.3 returns False in Python (and most languages). This causes bugs in financial calculations, comparisons, and accumulation loops. The actual result is 0.30000000000000004.

Solution

Use the appropriate tool for your precision needs:

# For approximate comparison
import math
math.isclose(0.1 + 0.2, 0.3) # True
math.isclose(a, b, rel_tol=1e-9, abs_tol=0.0)

# For exact decimal arithmetic (finance)
from decimal import Decimal
Decimal('0.1') + Decimal('0.2') == Decimal('0.3') # True
# IMPORTANT: use strings, not floats: Decimal(0.1) is still imprecise

# For money: use integers (cents)
price_cents = 299 # $2.99
total_cents = price_cents * quantity
total_dollars = total_cents / 100

Why

IEEE 754 floating point cannot exactly represent most decimal fractions. 0.1 in binary is a repeating fraction (like 1/3 in decimal). The tiny rounding errors accumulate with arithmetic operations.

Gotchas

  • Decimal('0.1') is exact but Decimal(0.1) inherits the float imprecision
  • Never use floats for money — use integer cents or Decimal
  • math.isclose uses relative tolerance by default — set abs_tol for near-zero comparisons

Code Snippets

Handling float precision

# Float comparison
import math
math.isclose(0.1 + 0.2, 0.3)  # True

# Exact decimal for money
from decimal import Decimal
total = Decimal('19.99') + Decimal('4.99')  # Decimal('24.98') exactly

# Integer cents (simplest for money)
price = 1999  # $19.99 in cents

Context

Any comparison or arithmetic with floating point numbers

Revisions (0)

No revisions yet.