12:04

# ROUND function

Compute average capacity of PC hard drive getting the result with two decimal digits.

Having executed the query

Console
Execute
`SELECT AVG(hd) AS avg_hd FROM pc;`
we'll obtain the result:

avg_hd
13.6666666666667

To get needed format of output, we can use ROUND function:

Console
Execute
`SELECT round(AVG(hd),2) AS avg_hd FROM pc;`

avg_hd
13.67

The second argument of the function determine the number of decimal places to which the result must be rounded.

The result demonstrates that we have arithmetic rounding. By the way, ROUND function has the third optional argument, which determines whether the result should be rounded (value of 0 - is default) or be truncated (the value other than 0).

I.e. if to rewrite the query as follows

Console
Execute
`SELECT round(AVG(hd),2,1) AS avg_hd FROM pc;`
то получим другой результат:

avg_hd
13.66

We can do rounding to any place, not only to a decimal one. For example, to get rounding to tens or hundreds and  so on, you can use negative value of second argument. The following query is rounding the result to tens.

Console
Execute
`SELECT round(AVG(hd),-1) AS avg_hd FROM pc;`

avg_hd
10

It should be noted that ROUND function does rounding but does not change the result type. I.e. if the first argument is of the dec(12,6) type, the result of rounding  will be of the same type, namely,

avg_hd
13.670000

It is easy to be convinced of it, having executed the query

`SELECT round(CAST(AVG(hd) AS dec(12,6)),2) AS avg_hd FROM pc;`

Therefore, if you wish to get rid of trailing zeroes, use conversion to the type required, for example, dec (12,2). Then we don't need ROUND function at all. :-)

Console
Execute
`SELECT CAST(AVG(hd) AS DEC(12,2)) AS avg_hd FROM pc;`