Skip to content
Advertisement

How to round an average to 2 decimal places in PostgreSQL?

I am using PostgreSQL via the Ruby gem ‘sequel’.

I’m trying to round to two decimal places.

Here’s my code:

I get the following error:

I get no error when I run the following code:

Does anyone know what I am doing wrong?

Advertisement

Answer

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 for numeric.

(In the above, note that float8 is just a shorthand alias for double 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 of round. Just append ::numeric for the shorthand cast, like round(val::numeric,2).


If you’re formatting for display to the user, don’t use round. Use to_char (see: data type formatting functions in the manual), which lets you specify a format and gives you a text result that isn’t affected by whatever weirdness your client language might do with numeric values. For example:

to_char will round numbers for you as part of formatting. The FM prefix tells to_char that you don’t want any padding with leading spaces.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement