Jimmy
Jimmy

Reputation: 571

SQL changing types

hi if i have the following :

table x {

 num1 double precision;
 num2 int;

}

and now i want to find out num2/num1 and round to 1 decimal place.

is there a way to do this in a SELECT query? for the double precision.. do i have to use numeric(4,1) or something like that?

Upvotes: 1

Views: 80

Answers (2)

Denis de Bernardy
Denis de Bernardy

Reputation: 78473

Expanding on mu's answer... Depending on your postgres version, you might need to add an explicit cast, because round(numeric, int) exists but round(float, int) does not:

select round(num1::numeric/num2::numeric, 1);

Upvotes: 1

mu is too short
mu is too short

Reputation: 434685

You can use round():

SELECT ROUND(num2/num1, 1) FROM x;

PostgreSQL will automatically upgrade the division to floating point when num1 is floating point:

> select 3/3.145927;
        ?column?        
------------------------
 0.95361399040727899916
(1 row)

And:

> select round(3/3.145927, 1);
 round 
-------
   1.0
(1 row)

Upvotes: 2

Related Questions