Memra

Numbers, rounding & casting

◈ 2 cards

Arithmetic, round(), and converting types with ::.

Numbers and conversions

Beyond + - * / Postgres gives you round(n), round(n, d) (d decimals), ceil, floor, abs, mod, power.

The :: operator casts a value to another type — '42'::int, price::int, now()::date. (The standard form CAST(price AS int) does the same.) Casting numeric to int rounds.

SELECT round(avg(price), 2) AS avg_price FROM books;
expressionresultround(14.99)15round(14.99, 1)15.0floor(14.99)1414.99::int15round(14.99 * 1.08, 2)16.19Casting numeric to int rounds — it does not truncate.
floor and a cast disagree on the same value: 14.99::int is 15 because casting rounds, while floor(14.99) is 14. Reach for round when you mean "nearest" and floor when you mean "down".
NORMAL ~/memra/learn/postgresql/numbers-and-casting utf-8 LF