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?
Try also the old syntax for casting,
works with any version of PostgreSQL.
There are a lack of overloads in some PostgreSQL functions, why (???): I think "it is a lack" (!), but @CraigRinger, @Catcall and the PostgreSQL team agree about "pg's historic rationale".
PS: another point about rounding is accuracy, check @IanKenney's answer.
Overloading as casting strategy
You can overload the ROUND function with,
Now your instruction will works fine, try (after function creation)
but it returns a NUMERIC type... To preserve the first commom-usage overload, we can return a FLOAT type when a TEXT parameter is offered,
Try
PS: checking
\df round
after overloadings, will show something like,The
pg_catalog
functions are the default ones, see manual of build-in math functions.Try with this:
Or simply:
According to Bryan's response you can do this to limit decimals in a query. I convert from km/h to m/s and display it in dygraphs but when I did it in dygraphs it looked weird. Looks fine when doing the calculation in the query instead. This is on postgresql 9.5.1.
PostgreSQL does not define
round(double precision, integer)
. For reasons @Catcall explains in the comments, the version of round that takes a precision is only available fornumeric
.(In the above, note that
float8
is 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
numeric
to use the two-argument form ofround
. Just append::numeric
for 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 atext
result that isn't affected by whatever weirdness your client language might do withnumeric
values. For example:to_char
will round numbers for you as part of formatting. TheFM
prefix tellsto_char
that you don't want any padding with leading spaces.Solution: You need to addtype cast then it will work
Ex:
round(extract(second from job_end_time_t)::integer,0)