BugHunt

0.1 + 0.2 == 0.3 is False

Python floats are binary floating point, so 0.1 and 0.2 are stored as approximations and their sum is 0.30000000000000004.

PythonType errors

What it means

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.

Common causes

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

Summing many small floats drifts further.

Breaks

assert sum([0.1] * 10) == 1.0

Works

assert math.isclose(sum([0.1] * 10), 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.

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.

Other common errors