TryBugHunt

0.1 + 0.2 == 0.3 is False

0.1 + 0.2 == 0.3 is False in Python means python floats are binary floating point, so 0.1 and 0.2 are stored as approximations and their sum is 0.30000000000000004.

PythonPattern: Type errors

How do I fix 0.1 + 0.2 == 0.3 is False?

In Python, 0.1 + 0.2 == 0.3 is False because floats are stored in binary, and 0.1 and 0.2 are only approximations. Their sum is 0.30000000000000004. Compare floats with math.isclose(a, b), format them with f"{x:.2f}" for display, and use decimal.Decimal("0.1") or integer cents for money.

  1. 1. Replace == on floatsWrite math.isclose(a + b, expected) instead of a + b == expected, including in assert statements.
  2. 2. Money calculationsint(19.99 * 100) gives 1998. Use Decimal("19.99") created from a string, or store whole cents as int.
  3. 3. Display, not valueIf the problem is only how it prints, format with f"{x:.2f}" or round(x, 2).

What does 0.1 + 0.2 == 0.3 is False mean?

A float can only hold numbers that are sums of powers of two, and 0.1 is not one of them, so Python stores the closest value. The difference is invisible until you compare with == or print more digits. Every language using standard floats behaves this way.

Why does 0.1 + 0.2 == 0.3 is False happen?

1. Comparing floats with ==

Two values that are equal on paper differ in the last bit.

Breaks

if a + b == expected:

Works

import math
if math.isclose(a + b, expected):

2. Money as floats

Errors add up, and int() then truncates them into whole cents.

Breaks

cents = int(19.99 * 100)   # 1998

Works

from decimal import Decimal
cents = int(Decimal("19.99") * 100)   # 1999

3. Testing a running total

Adding many small floats one at a time drifts further.

Breaks

total = 0.0
for _ in range(10):
    total += 0.1
assert total == 1.0

Works

total = 0.0
for _ in range(10):
    total += 0.1
assert math.isclose(total, 1.0)

How to find it in your own code

Use math.isclose() for comparisons, round() or a format spec such as f"{x:.2f}" for display, and decimal.Decimal (created from strings) or integer cents for money.

Try it: fix this bug

medium

totals_match(0.1, 0.2, 0.3) returns False. totals_match(1, 2, 3) works.

def totals_match(a, b, expected):
    return a + b == expected
Open with hintsRuns in your browser. No account needed.

Still not sure why yours breaks?

Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.

Related error guides

View all type errors →