Sub topic 4
Converting between numeric types
This chapter assumes you know basic SQL and the common PostgreSQL types, and that you can run queries in psql. It builds on the cast syntaxes from the previous chapters (CAST, :: and typed literals). It covers what happens to a number when it moves between smallint, integer, bigint, numeric, real and double precision.
The numeric types and what they promise
The numeric types fall into three groups, and conversion behavior depends on which group you cross.
| Group | Types | Behavior |
|---|---|---|
| Exact integers | `smallint`, `integer`, `bigint` | Fixed range, no fraction |
| Exact decimals | `numeric(p,s)`, `numeric` | Arbitrary precision, decimal arithmetic |
| Approximate floats | `real`, `double precision` | Binary floating point, 6 and 15 significant digits |
Moving within a group usually changes only range. Moving between groups can change precision, rounding or both.
The upward arrows are safe because every value fits in the wider type, apart from the precision loss when a large bigint or numeric becomes a float. The downward arrows can lose data, so PostgreSQL allows them only in assignment contexts such as INSERT, or when you write the cast yourself. The pg_cast catalog records these rules, and a later chapter covers them in detail.
Range overflow
Narrowing an integer checks the range and raises an error. It never wraps around.
SELECT 2147483647::integer AS max_int;
SELECT 2147483648::integer AS too_big; -- ERROR: integer out of range
SELECT 40000::smallint AS too_big; -- ERROR: smallint out of rangeThe literal 2147483648 is first typed as bigint because it does not fit in integer. The cast to integer then fails.
Arithmetic overflows the same way. SELECT 2147483647 + 1; fails with integer out of range, because both operands are integer and so is the result. Cast one operand to bigint to get a bigint result:
SELECT 2147483647::bigint + 1 AS ok;Rounding when a fraction is dropped
Casting numeric to an integer type rounds to the nearest integer. Ties round away from zero.
SELECT 2.5::numeric::integer AS a, -- 3
3.5::numeric::integer AS b, -- 4
(-2.5)::numeric::integer AS c; -- -3Floating-point values round differently. real and double precision use the C library's round-to-nearest, with ties going to the even neighbor.
SELECT 2.5::float8::integer AS a, -- 2
3.5::float8::integer AS b, -- 4
0.5::float8::integer AS c; -- 0The same number gives different integers depending on its source type. If you need a specific rule, do not rely on the cast. Call a function that states the rule:
SELECT round(2.5::numeric) AS round_numeric, -- 3
round(2.5::float8) AS round_float, -- 2
trunc(-2.7::numeric) AS truncated, -- -2
floor(-2.7::numeric) AS floored, -- -3
ceil(-2.7::numeric) AS ceiled; -- -2Assignment casts round the same way. This statement stores 4, not an error:
CREATE TABLE counts (n integer);
INSERT INTO counts VALUES (3.7);
SELECT n FROM counts; -- 4This is a common source of silent data change. If a column should never receive fractions, check the value before you insert it.
Special float values
numeric, real and double precision can hold NaN. Floats can also hold Infinity and -Infinity. None of these has an integer form, so the cast fails.
SELECT 'NaN'::numeric::integer; -- ERROR: cannot convert NaN to integer
SELECT 'Infinity'::float8::integer; -- ERROR: integer out of rangeFilter these values out before casting, for example with WHERE x = x AND x <> 'Infinity' for floats. NaN is equal to itself in PostgreSQL, so test for it with x <> 'NaN'.
Precision and scale in numeric
A numeric(p,s) type has p total significant digits and s digits after the decimal point. Casting to a narrower scale rounds. Casting to a precision that cannot hold the integer part raises an error.
SELECT 123.456::numeric(5,2) AS rounded; -- 123.46
SELECT 1234.567::numeric(5,2) AS overflow; -- ERROR: numeric field overflowThe error message says the absolute value must be less than 10^3 for numeric(5,2). The integer part gets p - s digits, which is 3 here.
An unconstrained numeric keeps whatever precision you give it. Use it when you do not want rounding to happen implicitly.
Mixing types in arithmetic
When an operator receives two different numeric types, PostgreSQL implicitly converts the one that is lower in the hierarchy. The hierarchy is smallint → integer → bigint → numeric → real → double precision.
SELECT pg_typeof(1 + 1::bigint) AS int_bigint, -- bigint
pg_typeof(1 + 1.5) AS int_numeric, -- numeric
pg_typeof(1.5 + 1.5::float8) AS num_float; -- double precisionInteger division truncates toward zero, which surprises many people:
SELECT 7 / 2 AS int_div, -- 3
-7 / 2 AS neg_int_div, -- -3
7::numeric / 2 AS num_div, -- 3.5000000000000000
7 / 2.0 AS lit_div, -- 3.5000000000000000
7 % 2 AS remainder; -- 1Cast at least one operand before dividing when you want a fractional result. Casting the result does not help, because (7 / 2)::numeric is already 3.
Converting between exact and approximate values
Going from numeric to a float is allowed implicitly, but it can lose exactness. Going from float to numeric is an assignment cast, and it uses the shortest decimal form that round-trips at the float's display precision, not the full binary value.
SELECT 0.1::float8::numeric AS from_float, -- 0.1
(0.1::float8 + 0.2::float8) = 0.3::float8 AS float_eq, -- false
(0.1::numeric + 0.2::numeric) = 0.3::numeric AS num_eq; -- trueUse numeric for money and any value where equality must be exact. Convert to floats only for scientific or statistical work where small errors are acceptable.
Large integers lose digits when they become real, because real has only about 6 decimal digits:
SELECT 123456789::real AS lost; -- 1.2345679e+08Use double precision if you need to keep integers up to about 2^53 exactly.
Common mistakes
- Expecting an integer cast of a float to truncate. It rounds, and the tie rule differs from
numeric. - Dividing two integers and expecting a decimal result.
- Casting a text value such as
'3.7'straight tointeger. The text goes through the integer input function and fails. Cast throughnumericfirst:'3.7'::numeric::integer. - Letting an assignment cast round values into an integer column without noticing.
- Using
realfor identifiers or counters that can exceed 16 million.
Exercise
What do 2.5::numeric::integer and 2.5::float8::integer return, and what does (7 / 2)::numeric return? Rewrite the last expression so it returns 3.5.
Show answer
The first returns 3, because numeric rounds ties away from zero. The second returns 2, because floating-point values round ties to the even integer. (7 / 2)::numeric returns 3, because the integer division happens before the cast. Use 7::numeric / 2 (or 7 / 2.0) to get 3.5000000000000000.
Exercise
A column is defined as price numeric(6,2). What happens when you insert 12345.678, and what happens when you insert 1234.567?
Show answer
Inserting 12345.678 fails with "numeric field overflow", because the integer part needs 5 digits and only 4 are available (6 minus 2). Inserting 1234.567 succeeds and stores 1234.57, because the extra scale is rounded.