NUMERIC Exact Versus Binary Float

Store money in NUMERIC and analytics in double precision: binary floats cannot represent 0.1 exactly, so repeated sums drift away from decimal results.

SqlData Integrity

Code

snippet
-- 金额用 NUMERIC(精确十进制);统计近似值才用 float8/double precision
CREATE TABLE ledger (
    id           bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    amount_cents numeric(12, 2) NOT NULL,  -- 精确到分,无舍入误差
    ratio        double precision             -- 近似统计量
);

-- 二进制浮点无法精确表示 0.1:三次相加不等于 0.3
SELECT (0.1::float8 + 0.2::float8) = 0.3::float8 AS float_equals;
SELECT (0.1::numeric + 0.2::numeric) = 0.3::numeric AS numeric_equals;

-- 聚合口径不同:SUM(numeric) 保持精确,SUM(double precision) 有累积误差
SELECT sum(amount_cents) AS exact_total FROM ledger;

-- 取舍规则:科学计算容忍近似用 float;钱、配额、计费用 numeric

How it works

Several statements share this file — SELECT / CREATE, with ledger among the objects involved.

Breaking the statements into their working parts: SUM aggregation; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.

Applying it

Run it in the ledger database context.

Statements that matter

CREATE TABLE ledger (
id           bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
amount_cents numeric(12, 2) NOT NULL,  -- 精确到分,无舍入误差
ratio        double precision             -- 近似统计量
);
SELECT (0.1::numeric + 0.2::numeric) = 0.3::numeric AS numeric_equals;
SELECT (0.1::float8 + 0.2::float8) = 0.3::float8 AS float_equals;

Interactive Tools for This Topic

FAQ

Which relations are involved here?
`ledger`.