Postgres round() function
Round numbers to a specified precision
The Postgres round()
function rounds numeric values to a specified number of decimal places or the nearest integer.
It can help maintain consistency in numerical data, simplify complex decimal numbers, and adjust the precision of calculations to meet specific requirements. It's particularly useful in financial calculations, data analysis, and for presenting numerical data in a more readable format.
Function signature
The round()
function has a simple form:
number
: The input value to be rounded. It can be of any numeric data type — integer, floating-point, or decimal.decimal_places
: An optional integer that specifies the number of decimal places to round to. If omitted, the input number is rounded to the nearest integer.
Example usage
Let's consider a table product_sales
that tracks sales data for various products. We'll use the round()
function to adjust the precision of our sales figures.
This query demonstrates using the round()
function to round sales amounts to the nearest integer and to two decimal places (cents).
Other examples
Using round() to calculate accurate percentages
The round()
function is often used when calculating and displaying percentages. For example, consider a table with sales data for different products. Let's calculate the percentage of total sales contributed by each product.
This query calculates each product's contribution to total sales and rounds the percentage to two decimal places. This avoids displaying overly precise percentages that can be misleading.
Combining round() with other functions
We can combine round()
with other functions for more complex calculations. For example, let's calculate the average order value and round it to the nearest dollar and the nearest cents:
Additional considerations
Rounding behavior
Postgres round()
function uses the half-round-up method for tie-breaking. This means that when the input is exactly halfway between two numbers, it rounds up to the higher number. For example:
This query rounds both 2.65 and 2.75 to the next higher number with one decimal place:
Financial calculations often require banker's rounding (also known as round-to-even) to minimize bias. If you need this behavior, you can implement it using a custom function or by combining round()
with other functions.
Performance implications
The round()
function is generally fast, but frequent use in large datasets might impact performance. If you need to round values frequently in queries, consider storing pre-rounded values in a separate column and creating a function index on it.
Alternative functions
ceil()
andfloor()
: These functions round up or down to the nearest integer, respectively.trunc()
: This function truncates a number to a specified number of decimal places without rounding.