← Back to SQL, page 9

sql-0168 · Medium mid

Why might SELECT 0.1 + 0.2 = 0.3 return false, and which type should hold money amounts?

0.1 and 0.2 have no exact binary floating-point representation, so their sum is 0.30000000000000004. SQLite's REAL and PostgreSQL's double precision show this. For money, use PostgreSQL's NUMERIC, which is exact decimal, or store integer minor units such as cents on any engine.

Full answer
sql
SELECT 0.1 + 0.2 = 0.3 AS equal, (0.1 + 0.2) - 0.3 AS difference;
equaldifference
05.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_equalfloat_equalfloat_sum
truefalse0.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;
exactshown
10.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