← Back to PostgreSQL, page 2

postgresql-0024 · Easy fresher

How does numeric(p, s) round values on insert, and when does it raise an overflow error?

numeric(p, s) stores at most p significant digits with s of them after the decimal point. Inserting more decimal places rounds to s digits, half away from zero; a value with too many digits before the point raises 'numeric field overflow'. numeric without parameters stores any precision exactly.

Full answer

Schema and sample rows:

sql
CREATE TABLE prices (label text, amount numeric(6,2));
sql
INSERT INTO prices VALUES ('a', 12.345), ('b', 12.344), ('c', -0.005), ('d', 9999.999 - 0.009); SELECT label, amount FROM prices ORDER BY label;

Result:

text
 label |  amount
-------+---------
 a     | 12.35
 b     | 12.34
 c     | -0.01
 d     | 9999.99
(4 rows)
sql
INSERT INTO prices VALUES ('e', 10000);

Output:

text
ERROR:  numeric field overflow
sql
SELECT round(2.5) AS r1, round(3.5) AS r2, round(2.5::float8) AS float_r, round(1234.5678, -2) AS hundreds;

PostgreSQL returns:

text
 r1 | r2 | float_r | hundreds
----+----+---------+----------
 3  | 4  | 2       | 1200
(1 row)

12.345 is rounded to 12.35 and 12.344 to 12.34, and -0.005 rounds away from zero to -0.01. The value 9999.99 fits exactly into numeric(6,2), which allows four digits before the point. 10000 needs five, so it fails with a numeric field overflow error. round() on numeric rounds halves away from zero (2.5 becomes 3), while round() on double precision uses the platform's round-half-even rule, so 2.5 becomes 2. A negative scale rounds to tens or hundreds.

sql
CREATE TABLE prices (label text, amount numeric(6,2));

INSERT INTO prices VALUES ('a', 12.345), ('b', 12.344), ('c', -0.005), ('d', 9999.999 - 0.009); SELECT label, amount FROM prices ORDER BY label;

INSERT INTO prices VALUES ('e', 10000);

SELECT round(2.5) AS r1, round(3.5) AS r2, round(2.5::float8) AS float_r, round(1234.5678, -2) AS hundreds;

Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.

Key points

  • numeric(p, s) rounds extra decimals
  • Halves round away from zero for numeric
  • Too many integer digits overflow
  • float rounding uses half-even
  • Negative scale rounds left of the point

Common mistakes

  • Choosing a precision too small for future amounts
  • Mixing float and numeric rounding rules

Follow-ups

  • How should currency columns be sized?
  • Why is unconstrained numeric slower?

Tips

  • Contrast numeric and float rounding