PostgreSQL – ROUND Function
In PostgreSQL, the ROUND()
function is used to round a numeric value to a specified number of decimal places or to the nearest integer. It allows you to round numbers based on your desired precision.
The basic syntax of the ROUND()
function is as below:
ROUND(numeric_expression [, decimal_places])
where numeric_expression
is the numeric value or expression that you want to round.
and decimal_places
(optional) is the number of decimal places to which you want to round the numeric expression. If omitted, the number will be rounded to the nearest integer.
Below are some examples of using the ROUND()
function:
- Rounding to the nearest integer:
SELECT ROUND(5.7) AS rounded_value;
This query will return 6
, as 5.7
is closer to 6
when rounding to the nearest integer.
- Rounding to a specified number of decimal places:
SELECT ROUND(3.1459, 2) AS rounded_value;
This query will return 3.15
, rounding 3.1459
to two decimal places.
- Rounding a negative number:
SELECT ROUND(-8.9) AS rounded_value;
This query will return -9
, as -8.9
is closer to -9
when rounding to the nearest integer.
- Using expressions as input:
SELECT ROUND(10 / 3.0, 2) AS rounded_value;
This query will return 3.33
, rounding the result of 10 / 3.0
to two decimal places.
The ROUND()
function is versatile and can be used in various scenarios where you need to adjust the precision of numeric values.
Keep in mind that the ROUND()
function returns the result as a numeric data type. If you need the result in a different data type, you can explicitly cast it to the desired type using the CAST()
or ::
operator. For example:
SELECT ROUND(3.1459, 2)::numeric(10, 1) AS rounded_numeric;
This query will return 3.1
as a numeric data type with a precision of 10 and one decimal place.