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.
Code
-- 金额用 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;钱、配额、计费用 numericHow 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
IEEE 754 ConverterConvert decimal floats to and from IEEE 754 single- and double-precision bit patterns in hex and binary.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Binary Text ConverterConvert UTF-8 text to 8-bit binary groups and decode binary back to text with strict validation.
FAQ
- Which relations are involved here?
- `ledger`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.