I am using PostgreSQL via the Ruby gem ‘sequel’.
I’m trying to round to two decimal places.
Here’s my code:
SELECT ROUND(AVG(some_column),2)
FROM table
I get the following error:
PG::Error: ERROR: function round(double precision, integer) does
not exist (Sequel::DatabaseError)
I get no error when I run the following code:
SELECT ROUND(AVG(some_column))
FROM table
Does anyone know what I am doing wrong?
PostgreSQL does not define
round(double precision, integer). For reasons @Mike Sherrill ‘Cat Recall’ explains in the comments, the version of round that takes a precision is only available fornumeric.(In the above, note that
float8is just a shorthand alias fordouble precision. You can see that PostgreSQL is expanding it in the output).You must cast the value to be rounded to
numericto use the two-argument form ofround. Just append::numericfor the shorthand cast, likeround(val::numeric,2).If you’re formatting for display to the user, don’t use
round. Useto_char(see: data type formatting functions in the manual), which lets you specify a format and gives you atextresult that isn’t affected by whatever weirdness your client language might do withnumericvalues. For example:to_charwill round numbers for you as part of formatting. TheFMprefix tellsto_charthat you don’t want any padding with leading spaces.