Full answer
sql
SELECT 0.1 + 0.2 = 0.3 AS equal, (0.1 + 0.2) - 0.3 AS difference;| equal | difference |
|---|---|
| 0 | 5.551115123125783e-17 |
SQLite stores 0.1 as a binary double, so the sum is slightly above 0.3; the difference is tiny but not zero. PostgreSQL treats the literal 0.1 as numeric, which is exact, unless you ask for double precision:
sql
SELECT 0.1 + 0.2 = 0.3 AS numeric_equal,
0.1::float8 + 0.2::float8 = 0.3::float8 AS float_equal,
0.1::float8 + 0.2::float8 AS float_sum;| numeric_equal | float_equal | float_sum |
|---|---|---|
| true | false | 0.30000000000000004 |
SQLite has no exact decimal type; DECIMAL(10,2) is accepted as a type name but gets NUMERIC affinity and stores floats or integers. So in SQLite, store cents as INTEGER:
sql
CREATE TABLE payments (id INTEGER PRIMARY KEY, amount_cents INTEGER NOT NULL);
INSERT INTO payments VALUES (1, 10), (2, 20);
SELECT SUM(amount_cents) = 30 AS exact, printf('%.2f', SUM(amount_cents) / 100.0) AS shown FROM payments;| exact | shown |
|---|---|
| 1 | 0.30 |
Floating point is fine for measurements where tiny errors do not matter. For balances, invoices and anything that must add up exactly, use exact types.
sql
SELECT 0.1 + 0.2 = 0.3 AS equal, (0.1 + 0.2) - 0.3 AS difference;
CREATE TABLE payments (id INTEGER PRIMARY KEY, amount_cents INTEGER NOT NULL);
INSERT INTO payments VALUES (1, 10), (2, 20);
SELECT SUM(amount_cents) = 30 AS exact, printf('%.2f', SUM(amount_cents) / 100.0) AS shown FROM payments;Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
- Binary floats cannot represent most decimal fractions exactly
- PostgreSQL NUMERIC is exact decimal
- SQLite has no exact decimal; store integer cents
- Floats are fine for measurements, not money
Common mistakes
- Comparing floats with =
- Declaring DECIMAL in SQLite and assuming exact arithmetic
Follow-ups
- How would you round money for display?
- What happens when you sum many REAL amounts?
Tips
- Mention integer cents as the portable answer