Occasionally, when selecting aggregate data (usually AVG()
) from a database, I'll get a repeating decimal such as:
2.7777777777777777
When I apply ROUND(AVG(x), 2
) to the value, I sometimes get a result like:
2.7800000000000002
I happen to know that the actual sample has 18 rows with SUM(x)
= 50. So this command should be equivalent:
SELECT ROUND(50.0/18, 2)
However, it produces the expected result (2.78). Why does rounding sometimes produce wrong results with aggregate functions?
In order to verify the above result, I wrote a query against a dummy table:
declare @temp table(
x float
)
insert into @temp values (1.0);
insert into @temp values (2.0);
insert into @temp values (1.0);
insert into @temp values (1.0);
insert into @temp values (1.0);
insert into @temp values (1.0);
insert into @temp values (1.0);
insert into @temp values (8.0);
insert into @temp values (9.0);
select round(avg(x), 2),
sum(x),count(*)
from @temp
I'm aware of the gotchas of floating point representation, but this simple case seems not to be subject to those.