Numeric Functions
Numeric functions round, measure and calculate: round(307.142857, 2) gives 307.14, ceil rounds up, mod gives a remainder. Money needs cents, averages need rounding, installments need splitting, and every one of these has a trap. Integer division throws away fractions; rounding a three-way split can lose a penny; and round behaves differently on exact and floating-point numbers. This lesson covers the everyday numeric functions with real Fee Tracker results, and the traps that catch even experienced developers.
In One Minute
round(x, 2)rounds to cents;ceilrounds up,floordown,truncjust cuts off digits.abs,mod(or%),power,sqrtandsigndo what their names say.- Integer divided by integer is an integer in PostgreSQL:
7 / 2is 3. Make one side a decimal:7 / 2.0. - Splitting money can lose cents to rounding: 400.00 in 3 parts of 133.33 adds up to 399.99.
to_char(x, 'FM$9,999.00')formats money for display.
Rounding
SELECT round(307.142857, 2) AS to_cents,
round(307.5) AS to_whole,
ceil(307.14) AS up,
floor(307.94) AS down,
trunc(307.98, 1) AS cut; to_cents | to_whole | up | down | cut
----------+----------+-----+------+-------
307.14 | 308 | 308 | 307 | 307.9
(1 row)| Function | Does | 307.14… becomes |
|---|---|---|
round(x, n) | Nearest, to n decimal places | 307.14 |
ceil(x) | Up to the next whole number | 308 |
floor(x) | Down to the whole number below | 307 |
trunc(x, n) | Cut off after n places, no rounding | 307.1 |
round(x) with no places rounds to a whole number. Use round(avg(amount_usd), 2) whenever an average is shown as money; avg alone returns many decimal places, as Aggregate Functions showed.
How Rounding Breaks Ties
round of an exact NUMERIC rounds halves away from zero; round of a floating-point number rounds halves to the nearest even number.
SELECT round(2.5) AS numeric_half,
round(2.5::double precision) AS float_half,
round(3.5::double precision) AS float_three_half; numeric_half | float_half | float_three_half
--------------+------------+------------------
3 | 2 | 4
(1 row)2.5 as NUMERIC rounds to 3, but as DOUBLE PRECISION it rounds to 2 ("banker's rounding"), while 3.5 rounds to 4. Money stored as NUMERIC, as SQL Data Types recommended, gets the rounding people expect.
Other Math Functions
SELECT abs(-57.14) AS absolute,
mod(17, 5) AS remainder,
17 % 5 AS remainder_too,
power(2, 10) AS two_to_ten,
sqrt(16) AS square_root,
sign(-3) AS sign_of; absolute | remainder | remainder_too | two_to_ten | square_root | sign_of
----------+-----------+---------------+------------+-------------+---------
57.14 | 2 | 2 | 1024 | 4 | -1
(1 row)abs is handy for "how far from the average, either way". mod gives the remainder, so mod(payment_id, 2) = 0 finds even ids. random() returns a random number from 0 up to 1 (PostgreSQL; RAND() in MySQL and SQL Server), so floor(random() * 6) + 1 rolls a die. Results that use random change every run, so they don't appear in examples here.
Integer Division
When both numbers are integers, PostgreSQL divides as integers and throws away the fraction.
SELECT 7 / 2 AS integer_division,
7 / 2.0 AS decimal_division,
-7 / 2 AS negative,
sum(grade) / count(grade) AS grade_average_wrong,
avg(grade) AS grade_average_right
FROM students; integer_division | decimal_division | negative | grade_average_wrong | grade_average_right
------------------+--------------------+----------+---------------------+---------------------
3 | 3.5000000000000000 | -3 | 9 | 9.6666666666666667
(1 row)7 / 2 is 3, not 3.5, and -7 / 2 is -3: the fraction is cut off toward zero. The students' grades add to 29, and 29 / 3 gives 9 as integers, while avg gives 9.666…. To get a decimal, make one side a decimal: write 2.0, or cast with ::numeric, as in sum(grade)::numeric / count(grade). SQL Server divides integers the same way; MySQL and Oracle return a decimal.
Splitting Money
Rounding each part of a split can make the parts add up to less, or more, than the whole. SQL Basics costs $400.00. In three installments:
SELECT round(400.00 / 3, 2) AS each_part,
round(400.00 / 3, 2) * 3 AS three_parts; each_part | three_parts
-----------+-------------
133.33 | 399.99
(1 row)Three payments of $133.33 total $399.99, a penny short. Real billing systems round all parts but one, and make the last part the remainder: $133.33, $133.33 and $133.34. Never assume rounded parts add back to the whole.
Formatting Money
to_char(number, format) turns a number into display text (PostgreSQL and Oracle):
SELECT student_id, sum(amount_usd) AS total,
to_char(sum(amount_usd), 'FM$9,999.00') AS display
FROM payments
GROUP BY student_id
ORDER BY student_id; student_id | total | display
------------+---------+-----------
101 | 1700.00 | $1,700.00
103 | 450.00 | $450.00
(2 rows)In the format, 9 is a digit, , a thousands separator, .00 two decimal places, and FM removes padding spaces. The result is text: format only for display, at the very end, and do all arithmetic on the numbers. MySQL uses FORMAT(x, 2), and SQL Server FORMAT(x, 'C', 'en-US').
Common Mistakes
Integer division. 7 / 2 is 3. Make one side a decimal.
Rounding parts of a total. Rounded parts may not add up; give the remainder to the last part.
Sorting formatted numbers. to_char returns text, which sorts wrongly. Sort by the number.
Showing a raw average. Round it: round(avg(x), 2).
Interview Corner
What does SELECT 7 / 2 return in PostgreSQL, and why?
3. Both operands are integers, so PostgreSQL performs integer division and discards the fraction. 7 / 2.0 or 7::numeric / 2 returns 3.5.
What's the difference between ROUND, CEIL, FLOOR and TRUNC?
ROUND goes to the nearest value, CEIL always up, FLOOR always down, and TRUNC simply removes digits without rounding.
How do you calculate a percentage from two integer counts?
Cast one count to a decimal before dividing, as in round(100.0 * late_count / total_count, 1), to avoid integer division returning 0.
Practice
Challenge: What percentage of payments were late (paid after their due date)? Show the late count, the total count, and the percentage rounded to one decimal place.
Show solution
SELECT count(*) FILTER (WHERE paid_on > due_on) AS late,
count(*) AS total,
round(100.0 * count(*) FILTER (WHERE paid_on > due_on) / count(*), 1) AS late_percent
FROM payments; late | total | late_percent
------+-------+--------------
2 | 7 | 28.6
(1 row)Two of seven payments were late: 28.6%. The 100.0 makes the division decimal; with 100 instead, 200 / 7 would give 28 as an integer.
Key Takeaways
| You want to | Write |
|---|---|
| Round to cents | round(x, 2) |
| Always up / down | ceil(x), floor(x) |
| A decimal division | 7 / 2.0, or sum(grade)::numeric / count(grade) |
| A percentage | round(100.0 * part / total, 1) |
| Money for display | to_char(x, 'FM$9,999.00') |
Was this tutorial helpful?