How to Round Numbers in SQL
Database:
Operators:
Table of Contents
Problem:
You want to round a number to a specific number of decimal places in SQL.
Example:
Our database has a table named product
with data in the following columns: id
, name
, and price_net
.
id | name | price_net |
---|---|---|
1 | bread | 2.34 |
2 | croissant | 1.22 |
3 | roll | 0.38 |
Suppose there’s a tax of 24% on each product, and you’d like to compute the gross price of each item (i.e., after taxes) and round the value to two decimal places.
Solution:
SELECT id, ROUND(price_net * 1.24, 2) as price_gross FROM product;
This query returns the gross price rounded to two decimal places:
id | price_gross |
---|---|
1 | 2.90 |
2 | 1.51 |
3 | 0.47 |
Discussion:
If you’d like to round a floating-point number to a specific number of decimal places in SQL, use the ROUND()
function. The first argument of this function is the column whose values you want to round; the second argument is optional and denotes the number of places to which you want to round. By default, if you don’t specify the second argument, the function rounds to the nearest integer.
In this example, we won’t specify the number of places to which we want to round the column:
SELECT id, ROUND(price_net * 1.24) as price_gross FROM product;
And here’s the corresponding result:
id | price_gross |
---|---|
1 | 3 |
2 | 2 |
3 | 0 |
Note that the rounding is done according to mathematical rules of rounding: the number is rounded to the nearest integer. 2.90
for the product with ID of 1 is rounded up to 3
, but 0.47
for the product with ID of 3 is rounded down to 0
.