Sub topic 4
Floating-point types and their rounding behavior
PostgreSQL has two inexact number types, real and double precision. This chapter explains how they store values, why the results can look wrong, and when they are still the right choice. It assumes you know basic SQL (SELECT, CREATE TABLE), can run queries in psql, and have read the previous chapter on exact numeric values.
The two types
Both types follow the IEEE 754 standard for binary floating point. A value is stored as a sign, an exponent and a binary fraction. Many decimal fractions, such as 0.1, have no finite binary representation, so the stored value is the nearest representable number.
| Type | Aliases | Size | Precision | Approximate range |
|---|---|---|---|---|
| `real` | `float4` | 4 bytes | about 6 decimal digits | 1e-37 to 1e+37 |
| `double precision` | `float8`, `float` | 8 bytes | about 15 decimal digits | 1e-307 to 1e+308 |
float(p) also exists. With p from 1 to 24 it means real. With p from 25 to 53 it means double precision. A bare float means double precision.
Unlike numeric(p,s), these types take no precision or scale modifiers. You cannot tell PostgreSQL to keep two decimal places.
Why results look wrong
The decimal literal 0.1 is not stored exactly. Adding two approximations gives another approximation, and the result may differ from the one you expect.
SELECT
0.1::double precision + 0.2::double precision AS float_sum,
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 query returns 0.30000000000000004, false and true. Since PostgreSQL 12, floating-point output uses the shortest text that converts back to the same stored value. The extra digits are therefore real. Older versions, and sessions that set extra_float_digits to 0 or lower, round the display to 15 digits and show 0.3. The stored value is the same, and the comparison is still false.
The mechanism is stored precision, not output formatting. A double precision value has 53 bits of fraction. Past that, neighboring values are farther apart than 1.
SELECT (1e16::double precision + 1) - 1e16 AS lost_by_double,
16777217::real AS real_integer;The first column is 0. At 1e16 the gap between adjacent doubles is 2, so adding 1 rounds back to 1e16. The second column shows 16777216. A real has 24 bits of fraction, so it cannot represent every integer above 2^24 (16,777,216).
Comparing floating-point values
Equality with = on computed floats is unreliable. Compare with a tolerance instead.
SELECT abs((0.1::double precision + 0.2) - 0.3) < 1e-9 AS close_enough;The tolerance depends on the magnitude of your data. An absolute tolerance of 1e-9 is meaningless for values near 1e12. For wide ranges, use a relative tolerance such as abs(a - b) <= 1e-9 * greatest(abs(a), abs(b)).
Two practical consequences follow:
- A
UNIQUEconstraint or aWHERE x = 0.3filter on float columns can miss rows that look identical when printed. - Grouping or joining on float columns is risky for the same reason. Join on integer or
numerickeys.
Rounding
round() behaves differently for the two families, and the difference surprises people.
SELECT round(2.5::double precision) AS float_round,
round(2.5::numeric) AS numeric_round,
round(3.5::double precision) AS float_round_even;The results are 2, 3 and 4. For double precision, round rounds exact halves to the nearest even number. This follows the C library function and can vary by platform. For numeric, it rounds halves away from zero. If a report must follow a stated rounding rule, convert to numeric first.
There is also no two-argument round(double precision, integer). Calling it raises an error saying the function does not exist. Cast to numeric:
SELECT round(2.675::double precision::numeric, 2) AS rounded;The cast from double precision to numeric uses 15 significant digits, so the input here becomes 2.675 and the result is 2.68. Casting a real uses 6 significant digits. That is not the same as rounding the exact stored binary value. Rounding in another language, such as Python, can give 2.67 for the same literal, because it works on the exact stored value.
Special values
IEEE floats include values that exact types lack.
SELECT 'NaN'::double precision = 'NaN'::double precision AS nan_equal,
'Infinity'::double precision > 1e308 AS inf_big,
'-0'::double precision = 0 AS neg_zero_equal;All three columns return true. NaN means "not a number". In IEEE 754, NaN is never equal to anything, including itself. PostgreSQL deliberately treats all NaN values as equal to each other and greater than every other value, so that sorting and indexing work. Be aware of this if you port a comparison from application code. Negative zero is stored distinctly but compares equal to zero.
Errors behave differently from the IEEE defaults:
SELECT 1.0::double precision / 0; -- ERROR: division by zero
SELECT 1e308::double precision * 10; -- ERROR: value out of range: overflow
SELECT 'abc'::double precision; -- ERROR: invalid input syntax for type double precision: "abc"PostgreSQL reports an error for division by zero and overflow instead of silently producing Infinity. You get Infinity or NaN only when you write them as input or when an operation receives them as input.
Aggregates over floats
sum() and avg() on float columns return double precision (sum(real) returns real). Addition of floats is not associative, so the order of rows can change the last digits. A parallel query plan may add values in a different order than a serial one, and the same query can give slightly different totals between runs. Summing numeric has no such drift. Sum money as numeric, and cast float columns to numeric before aggregating if exact totals matter.
When floating point is the right choice
Float types are not "bad numerics". They are fast, compact, and cover a very wide range. Use them when the data is itself approximate or when speed over large volumes matters:
- Physical measurements such as temperature, voltage or sensor readings, which already carry measurement error.
- Scientific and statistical values, such as model scores or probabilities, where you need a huge range rather than exact decimal digits.
- Geographic coordinates stored as latitude and longitude.
- Large analytical columns where
numericarithmetic cost would dominate.
Avoid them for prices, balances, tax, quantities that must add up, and anything compared with =. For those, use numeric(p,s), or store integer cents in a bigint.
Choosing between real and double precision
Prefer double precision unless storage is a measured problem. real saves 4 bytes per value, but its roughly 6 digits are easy to exhaust. A real cannot hold a timestamp in epoch seconds or a large integer count exactly. Literals without a cast, such as 1.5, are numeric, not float. Mixing a numeric with a double precision operand converts the result to double precision, so one float operand makes the whole expression inexact.
Exercise
A table has a column price double precision. The query SELECT * FROM items WHERE price = 19.99 returns no rows, although the application inserted a row with price 19.99. Give the cause and two ways to fix it.
Show answer
The inserted 19.99 was stored as the nearest binary double, and the literal 19.99 in the query is numeric, so the comparison converts the numeric to double precision and the values may differ in the last bits, or earlier arithmetic may have changed the stored value. Fix 1: change the column to numeric(12,2), which stores 19.99 exactly and compares exactly. Fix 2: keep the float but compare with a tolerance, for example WHERE abs(price - 19.99) < 0.005. Storing integer cents in a bigint also works.
Exercise
What do round(0.5::double precision) and round(0.5::numeric) return, and why do they differ?
Show answer
The double precision call returns 0 and the numeric call returns 1. For double precision, round rounds an exact half to the nearest even number (0). For numeric, it rounds halves away from zero (1).