Skip to content

Python Float Comparison Precision Fix

DodaTech Updated 2026-06-24 3 min read

In this tutorial, you'll learn about Python Float Comparison Precision Fix. We cover key concepts, practical examples, and best practices.

Floating-point arithmetic in Python produces results like 0.1 + 0.2 == 0.3 returning False. This is not a bug — it is inherent to how IEEE 754 floating-point numbers work. Direct equality comparison of floats is unreliable.

The Problem

a = 0.1 + 0.2
b = 0.3
print(f"a = {a}, b = {b}")
print(f"a == b: {a == b}")

Output:

a = 0.30000000000000004, b = 0.3
a == b: False

Wrong Code

# WRONG — direct float comparison
def calculate_tax(amount, rate=0.1):
    return amount * rate

total = 100 * 0.1
if total == 10.0:
    print("Tax calculated correctly")

Right Code

import math

a = 0.1 + 0.2
b = 0.3

# Use math.isclose for float comparison
if math.isclose(a, b, rel_tol=1e-9):
    print(f"{a} is close to {b}")

Expected output:

0.30000000000000004 is close to 0.3

Step-by-Step Fix

Step 1: Understand the precision issue

# Display full precision
print(f"0.1 + 0.2 = {0.1 + 0.2:.20f}")
print(f"0.3      = {0.3:.20f}")

Step 2: Use math.isclose for comparison

import math

print(math.isclose(0.1 + 0.2, 0.3))  # True
print(math.isclose(0.1, 0.1000000001, rel_tol=1e-6))  # True

Step 3: Use Decimal for exact arithmetic

from decimal import Decimal

a = Decimal('0.1') + Decimal('0.2')
b = Decimal('0.3')
print(f"a == b: {a == b}")  # True

# Decimal is exact but slower than float

Step 4: Compare with tolerance manually

def approx_equal(a, b, tolerance=1e-10):
    return abs(a - b) < tolerance

print(approx_equal(0.1 + 0.2, 0.3))  # True

Step 5: Round before comparison

value = 0.1 + 0.2
rounded = round(value, 2)
print(rounded == 0.3)  # True

Step 6: Use integer arithmetic where possible

# Instead of floats for currency
cents = 10 + 20  # represents 0.10 + 0.20
print(cents == 30)  # True — exact integer comparison

Prevention Tips

  • Never compare floats directly with ==
  • Use math.isclose() with appropriate tolerances
  • Use Decimal for financial calculations
  • Use integers for currency (cents, pennies)
  • Be aware that float precision limits to about 15-17 significant digits

Common Mistakes with float comparison

  1. Using return to exit a function early instead of wrapping a pure value in the monad
  2. Mixing let bindings with <- bindings in do notation, producing type errors
  3. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors

These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### Why does 0.1 + 0.2 not equal 0.3 in Python?

Floating-point numbers are represented in binary (base 2), and 0.1 is a repeating fraction in binary, just like 1/3 is in decimal. The approximation errors accumulate differently for 0.1+0.2 vs 0.3, causing the comparison to fail.

Should I use Decimal for all numeric operations?

No. Decimal is about 10-100x slower than float. Use floats for scientific calculations, graphics, machine learning, and most general math. Use Decimal for financial calculations, tax computations, and any application where exact decimal representation is required.

How does math.isclose work?

math.isclose(a, b, rel_tol, abs_tol) returns True if a and b are close within relative tolerance (default 1e-9) or absolute tolerance. It handles edge cases like NaN, infinity, and zero correctly. Use abs_tol for values near zero where relative tolerance fails.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro