liveBook · Manning

Floating-point arithmetic

As explained in PostgreSQL Mistakes and How to Avoid Them

A floating-point data type stores approximate real-number values using finite binary or decimal precision.

Floating-point types such as real and double precision store inexact approximations. They are therefore unsafe for exact monetary amounts, where rounding errors can produce incorrect balances or charges. section 3.6

The tempting percentage calculation

A literal calculation such as SELECT 99.99 * 0.25; returns 24.9975. Applying the same expression to a money column displays £25.00, but that presentation does not make the underlying arithmetic suitable for exact currency. Store monetary amounts as NUMERIC or DECIMAL instead, and keep the currency in an adjacent column. section 3.6

SELECT 99.99 * 0.25;
 ?column?
----------
  24.9975
(1 row)

Inspect the unrounded result of multiplying a monetary-looking value by a fraction. section 3.6

Treat floating-point types as a data-modeling choice rather than a harmless spelling variation:

  • Use NUMERIC instead of MONEY for exact monetary values; PostgreSQL treats NUMERIC and DECIMAL equivalently. section 3.6
  • During migrations, map source types by definition and behavior, not by matching names; improper mappings can lose precision or produce incorrect calculations. section 10.5

How PostgreSQL Mistakes and How to Avoid Them covers it

How deep it goes
Explains approximation and rounding consequences with SQL results, but stops short of floating-point representation internals.
Examples
Uses percentage multiplication, a money-column calculation, and cross-database type mappings to expose precision problems.
What it assumes
Assumes PostgreSQL type awareness and teaches explicit distinctions among numeric, integer, and floating-point types.
What you can do after
Evaluate monetary schemas and migration mappings, then choose NUMERIC or DECIMAL when exact amounts are required.
How it connects
Connects floating-point types with NUMERIC, DECIMAL, MONEY, data type conversion, and database migration.

Also explained in

Compare how 20 books explain floating-point arithmetic →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of PostgreSQL Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.