Sub topic 4
Floating-Point Types and Their Rounding Behavior
Assume you know basic SELECT, CREATE TABLE, and PostgreSQL casts. This chapter focuses on real and double precision, which store approximate numbers.
What floating-point types are
A floating-point type stores a number using a sign, a significant part, and an exponent. This format can represent very large and very small values efficiently, but it cannot represent every decimal fraction exactly.
PostgreSQL provides two floating-point types:
| Type | Approximate decimal precision | Typical storage |
|---|---|---|
| `real` | 6 decimal digits | 4 bytes |
| `double precision` | 15 decimal digits | 8 bytes |
double precision is usually the practical default when you need an approximate number. Use real only when lower storage matters and its lower precision is acceptable.
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 first expression returns false on typical PostgreSQL systems. The second returns true. The decimal values 0.1 and 0.2 have no exact binary floating-point representation, so their stored approximations add to a value slightly different from the approximation of 0.3.
Rounding and comparisons
Floating-point arithmetic rounds intermediate results to the available precision. Repeated calculations can accumulate small errors.
SELECT
1.0::double precision / 3 AS one_third,
(1.0::double precision / 3) * 3 AS back_again,
(1.0::double precision / 3) * 3 = 1.0::double precision AS exact_match;Do not test floating-point values for exact equality when a calculated result is expected. Compare with a tolerance instead:
SELECT abs(
(1.0::double precision / 3) * 3 - 1.0::double precision
) < 1e-15 AS close_enough;The tolerance should match the scale and accuracy required by your application. A tolerance that is too small acts like an exact comparison. One that is too large can treat meaningfully different values as equal.
Special values and schema choices
Floating-point columns can represent Infinity, -Infinity, and NaN in addition to ordinary numbers. These values may complicate sorting, filtering, and application validation. Add a CHECK constraint when your domain requires finite values.
CREATE TABLE sensor_readings (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
reading double precision NOT NULL,
recorded_at timestamptz NOT NULL DEFAULT now(),
CHECK (isfinite(reading))
);The choice can be viewed as a trade-off:
Exercise
Exercise
Which type should you choose for a product price, and which type is usually suitable for a temperature reading?
Show answer
Use numeric, such as numeric(12,2), for the product price. Use double precision for the temperature when small approximation errors are acceptable.