Number Functions & Math
Arithmetic
+, -, *, /, % (remainder), ^ (power)
⚠️ Integer / integer = integer: 5 / 2 = 2. Make one side decimal: 5 / 2.0, 5::numeric / 2
Rounding
| Function | 7.456 | -7.456 |
|---|---|---|
round(x) | 7 | -7 |
round(x, 2) | 7.46 | -7.46 |
ceil(x) | 8 | -7 |
floor(x) | 7 | -8 |
trunc(x, 1) | 7.4 | -7.4 |
- Round only for display or final results, not in the middle of calculations
Other maths functions
abs(x)– absolute valuemod(a, b)ora % b– remainderpower(a, b),sqrt(x),cbrt(x),exp(x),ln(x),log(x)greatest(a, b, c),least(a, b, c)– max/min across columns (not rows)random()– 0 ≤ x < 1; random integer 1–6:floor(random() * 6 + 1)sign(x)– -1, 0 or 1div(a, b)– integer division
Percentages
round(100.0 * part / total, 1) – multiply by 100.0 first so the division is decimal
Avoid division by zero
a / NULLIF(b, 0) – returns NULL instead of an error when b is 0
Formatting numbers for display
to_char(1234567.5, 'FM9,999,999.00')→1,234,567.50(FMremoves padding)- Currency formatting is often better done in the app (
Intl.NumberFormat) - Cast to a type:
amount::int,round(amount)::text
Example
SELECT round(7.456, 2) AS r2, -- 7.46
ceil(7.1) AS up, -- 8
floor(7.9) AS down, -- 7
trunc(-7.9) AS cut, -- -7
abs(-250) AS absolute,-- 250
17 % 5 AS remainder, -- 2
2 ^ 10 AS power, -- 1024
greatest(3, 9, 4) AS biggest; -- 9
-- Integer division trap
SELECT 5 / 2 AS int_div, 5 / 2.0 AS dec_div, round(5::numeric / 3, 2) AS third; -- 2 | 2.5000000000000000 | 1.67
-- Share of each user's budget already spent in November
SELECT u.name,
u.monthly_budget,
sum(e.amount) AS spent,
round(100.0 * sum(e.amount) / NULLIF(u.monthly_budget, 0), 1) AS pct_used
FROM users u
JOIN expenses e ON e.user_id = u.id
WHERE e.spent_on >= '2026-11-01'
GROUP BY u.id
ORDER BY pct_used DESC;
-- Ravi 11700 / 25000 → 46.8% ...
-- VAT and rounded totals
SELECT title, amount,
round(amount * 0.13, 2) AS vat,
round(amount * 1.13) AS total_rounded
FROM expenses WHERE user_id = 2 LIMIT 3;
-- Pretty number formatting
SELECT to_char(1234567.5, 'FM9,999,999.00') AS formatted; -- 1,234,567.50
-- Random dice roll
SELECT floor(random() * 6 + 1)::int AS dice;