Sub topic 3
Exact decimals with numeric
This chapter assumes you can write basic SELECT, INSERT and CREATE TABLE statements, can run queries in psql or another PostgreSQL client, and know what a column and a constraint are. You should also know the integer types from the previous chapter. Here you will learn how numeric stores decimal values exactly, how precision and scale work, how rounding behaves, and which mistakes show up most often.
Why numeric exists
Integer types hold whole numbers only. Floating-point types hold fractions, but they store values in binary, so many decimal fractions such as 0.1 cannot be represented exactly. For money, tax rates, measurements that must match a ledger, and anything you compare for equality, you want decimal arithmetic that gives the answer a person would calculate on paper.
numeric (also spelled decimal, which is identical in PostgreSQL) stores decimal digits exactly. The query below compares the two approaches.
SELECT
0.1::double precision + 0.2::double precision = 0.3::double precision AS float_equal,
0.1::numeric + 0.2::numeric = 0.3::numeric AS numeric_equal;The result is false for float_equal and true for numeric_equal. The next chapter covers why floating point behaves this way. For now, treat numeric as the default choice whenever a value is a decimal that must be exact.
Precision and scale
You declare a numeric column with two type modifiers: numeric(precision, scale).
- Precision is the total number of significant digits the value can hold.
- Scale is how many of those digits come after the decimal point.
So numeric(12,2) holds up to 12 digits, 2 of them after the point. That leaves 10 digits before the point, so the largest value is 9,999,999,999.99.
| Declaration | Meaning | Example values stored |
|---|---|---|
| `numeric(12,2)` | 12 digits, 2 after the point | `1234.50`, `0.07` |
| `numeric(5,0)` or `numeric(5)` | 5 digits, no fractional part | `42`, `99999` |
| `numeric(3,5)` | 3 digits, all after the point, with leading zeros allowed | `0.00123` |
| `numeric` | No limit declared | Any value, with its own scale |
A scale larger than the precision, such as numeric(3,5), is allowed in current PostgreSQL versions. It means the value must be less than 0.001 in absolute value. A negative scale, such as numeric(5,-2), is also allowed and rounds to the left of the decimal point. Both are rare in practice.
The orders table from this tutorial uses the type like this:
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_email text NOT NULL,
total numeric(12,2) NOT NULL CHECK (total >= 0),
is_paid boolean NOT NULL DEFAULT false,
created_at timestamptz NOT NULL DEFAULT now()
);The total column is exact, always shows two decimal places, and the CHECK constraint rejects negative totals.
What happens on insert
PostgreSQL applies the declared scale and precision when a value is stored.
- If the value has more fractional digits than the scale, PostgreSQL rounds it to the scale.
- If the value has fewer fractional digits, PostgreSQL pads it with zeros.
- If, after rounding, the value has more digits before the point than precision minus scale allows, PostgreSQL raises an error.
CREATE TEMP TABLE price_demo (price numeric(5,2));
INSERT INTO price_demo VALUES (3.14159); -- stored as 3.14
INSERT INTO price_demo VALUES (7); -- stored as 7.00
INSERT INTO price_demo VALUES (2.999); -- stored as 3.00
SELECT price FROM price_demo;
INSERT INTO price_demo VALUES (12345.6);
-- ERROR: numeric field overflow
-- DETAIL: A field with precision 5, scale 2 must round to an absolute value less than 10^3.Notice that 2.999 becomes 3.00. The rounding happens before the overflow check, so a value that rounds up into a new digit position can overflow even if it looked like it fit. For example, 999.999 into numeric(5,2) rounds to 1000.00, which needs six digits, and raises an error.
Rounding rules
PostgreSQL's numeric rounds halves away from zero. This is the rule many people learn in school, and it applies when you insert into a constrained column and when you call round().
SELECT round(2.5) AS r1, -- 3
round(3.5) AS r2, -- 4
round(-2.5) AS r3, -- -3
round(2.675, 2) AS r4; -- 2.68The same call with double precision input rounds halves to even on most platforms, so round(2.5::double precision) returns 2. If a result differs from what you expect, check whether one of the inputs is a floating-point value.
You can also round or cut off at a chosen digit with round(x, n) and trunc(x, n). ceil() and floor() give whole numbers.
Arithmetic and result scale
Arithmetic on numeric values is exact for addition, subtraction and multiplication. The scale of the result follows predictable rules:
- Addition and subtraction: the result scale is the larger of the two input scales.
- Multiplication: the result scale is the sum of the two input scales.
- Division: PostgreSQL picks a scale that gives at least 16 significant digits, so results are accurate but may be long.
SELECT 1.10 + 2.2 AS add_result, -- 3.30
1.5 * 2.25 AS mul_result, -- 3.375
10::numeric / 3 AS div_result; -- 3.3333333333333333Division can still produce a repeating decimal that cannot be exact. In that case, round the result explicitly to the scale your application needs, for example round(total / 3, 2). Splitting a payment into three parts this way can leave a one-cent difference, so decide where the remainder goes.
Mixing numeric with other types
When you combine types in one expression, PostgreSQL converts to a common type.
numericwithintegerorbigint: the integer is converted tonumeric. The result is exact.numericwithdouble precisionorreal:numericis converted to floating point. The result is not exact.
The second rule is the most common source of silent precision loss. A single double precision operand in a money calculation turns the whole expression into floating-point arithmetic.
SELECT pg_typeof(1.5::numeric + 1) AS with_int, -- numeric
pg_typeof(1.5::numeric + 1.0::double precision) AS with_float; -- double precisionUnquoted literals such as 0.1 are typed as numeric, so plain decimal literals are safe. The danger comes from columns or function results that are floating point. Check with pg_typeof() when in doubt.
Special values
numeric supports NaN (not a number) in all versions, and Infinity and -Infinity in PostgreSQL 14 and later. NaN compares equal to itself in PostgreSQL, and sorts greater than every other value, which differs from some other systems. Constrained columns such as numeric(12,2) accept NaN, but a CHECK (total >= 0) does not reject it, because NaN sorts above all numbers. Add AND total <> 'NaN' to the check, or use total BETWEEN 0 AND 9999999999.99, if you must exclude it.
Storage and performance
numeric is stored as a variable-length value. Storage grows with the number of digits, roughly 2 bytes per four decimal digits plus a small header. It is slower than integer, bigint and floating-point types because arithmetic is done in software, not directly by the CPU. For most business tables the difference is invisible. It matters when you sum or multiply hundreds of millions of values in analytics queries.
An alternative is to store money as integer minor units, such as cents in a bigint. That is fast and exact, but you must convert on every input and output, and it does not suit values with varying scale such as exchange rates. numeric(p,s) is usually the clearer choice.
Common errors
- Declaring
numericwith no modifiers for money. Each value keeps whatever scale it was inserted with, so1.5and1.50can both exist. Declare the scale you need. - Counting precision wrong.
numeric(5,2)holds values up to 999.99, not 99999.99. Precision includes the fractional digits. - Mixing in
double precision. A float column in the expression makes the result approximate. - Forgetting that rounding precedes the overflow check. Values just under a power of ten can fail on insert.
- Assuming division is exact. Round the result and plan for remainders.
- Using
numericas a key. Usebigintoruuidfor identifiers. Integers are faster and have no scale to worry about.
Practice
Exercise
A column is declared as numeric(6,3). What is the largest value it can hold, and what happens when you insert 99.9996?
Show answer
The column has 6 digits, 3 after the point, so 3 before it. The largest value is 999.999. Inserting 99.9996 rounds to 100.000 at scale 3. That has 3 digits before the point, so it fits, and the stored value is 100.000.
Exercise
A query computes price * rate, where price is numeric(10,2) and rate is a double precision column. What type is the result, and how would you keep the calculation exact?
Show answer
The result is double precision, because numeric is converted to floating point when mixed with it, so the result is approximate. To keep it exact, store rate as numeric (for example numeric(6,4)) or cast it with rate::numeric before multiplying, then round the result to the scale you need.