How to Round an Average to 2 Decimal Places in PostgreSQL

There are some real-time cases when we want to find the average of some entities and then round these averages to some specified decimal places. The most prominent/significant use case of this statement is calculating the CGPA. When calculating CGPA, we have to find the average first then we round it up to 2 decimal places. This post will demonstrate to us how we can round an average to 2 decimal numbers. Let’s get started.

How to Round an Average to 2 Decimal Places in PostgreSQL?

To find the average of entities, we use an aggregate function that is the “AVG() function”. The AVG() function takes in the name of the column and returns the average of all the numbers of the column. The fundamental/basic structure of the AVG() function is:

AVG(col_name);

To round a number to a certain decimal place we use the ROUND() function. We can write the syntax of the ROUND() function in two different ways. The first one is:

ROUND(Num dp or numeric)

This syntax only takes one parameter which is the number it will round and returns the nearest integer. In this syntax, you can not provide the parameter for the number of decimal places you want to round up to. The parameter passed into the function must be of DOUBLE PRECISION or Numeric data type.

The second syntax is:

ROUND(Num numeric, decimal_places int)

This syntax has two parameters defined in the function. The first parameter is the number that needs to be rounded off in numeric data type and the second parameter is the integer specifying the number of decimal places the rounding off should occur.

So now how can we round an average up to 2 decimal places using these functions? The concept will be more clear using an example. Let's move towards an example.

Example: Rounding an Average to 2 Decimal Places in PostgreSQL

Consider the table named “test_scores” containing the data and score records for candidates who appeared in the entrance test of a high school. That table looks like this:

img

Now we can find the average of scores obtained in the test and round it up to 2 decimal places:

SELECT ROUND(AVG(candidate_score), 2)
FROM test_scores;

We have written the AVG() function in the ROUND() function to get the average rounded up. We have specified “2” as a second parameter in the ROUND() function in order to get the average rounded up to 2 decimal places. The output for the query is:

img

So the query returned the average marks that candidates obtained, in the test rounded, up to 2 decimal places.

This is how we can average up to two decimal points.

Conclusion

To find the average of a column we use the AVG() function taking the name of the column as a parameter. The ROUND() function rounds off a specified number up to particular decimal places. To get the rounded average up to 2 decimal places, we use both functions simultaneously. In this post, we have elaborated on how can we get the rounded average up to 2 decimal places.