0
0
PythonDebug / FixBeginner · 3 min read

How to Handle Floating Point Precision in Python Correctly

Floating point precision errors happen because computers store numbers in binary, which can't exactly represent some decimals. To handle this in Python, use the decimal module for exact decimal arithmetic or round results with round() to control precision.
🔍

Why This Happens

Computers store floating point numbers in binary, which cannot exactly represent many decimal fractions. This causes small rounding errors that show up when you do math with floats.

python
a = 0.1 + 0.2
print(a == 0.3)
print(a)
Output
False 0.30000000000000004
🔧

The Fix

Use Python's decimal.Decimal for precise decimal math or round floats to a fixed number of decimal places to avoid unexpected results.

python
from decimal import Decimal

a = Decimal('0.1') + Decimal('0.2')
print(a == Decimal('0.3'))
print(a)

# Or using rounding
b = 0.1 + 0.2
print(round(b, 1) == 0.3)
print(round(b, 1))
Output
True 0.3 True 0.3
🛡️

Prevention

Always use decimal.Decimal when exact decimal precision is needed, such as in financial calculations. For general use, round floats before comparing or displaying. Avoid direct equality checks on floats without rounding.

⚠️

Related Errors

Similar issues include comparing floats directly, which can fail due to tiny differences. Use math.isclose() for approximate comparisons. Also, beware of accumulating floating point errors in loops or sums.

python
import math

x = 0.1 + 0.2
print(math.isclose(x, 0.3))
Output
True

Key Takeaways

Floating point numbers can have tiny precision errors due to binary storage.
Use the decimal module for exact decimal arithmetic when needed.
Round floats before comparing or displaying to avoid surprises.
Avoid direct equality checks on floats without rounding or tolerance.
Use math.isclose() for safe approximate float comparisons.