Re: dividing integers not producing decimal fractions - Mailing list pgsql-general

From Martijn van Oosterhout
Subject Re: dividing integers not producing decimal fractions
Date
Msg-id 20061105100731.GB3979@svana.org
Whole thread Raw
In response to Re: dividing integers not producing decimal fractions  (rloefgren@forethought.net)
List pgsql-general
On Fri, Nov 03, 2006 at 02:03:59PM -0800, rloefgren@forethought.net wrote:
> You're right (I dug around in the documentation and edjoocated myself).
> However:

<snip>

> sales=# select 1/2::float;
>  ?column?
> ----------
>       0.5
> (1 row)

Note that in this case the "float" cast only applies to the last
number. That's why you get this:

> sales=# select (1/2)*4::float;
>  ?column?
> ----------
>         0
> (1 row)

The integer divide happens first. It is best to apply the cast to the
first element of the expression, as expressions are parsed
left-to-right, so:

select (1::float/2)::4;

Works better. However, mostly it's better to explicitly make all your
constants non-integer if that's what you mean. This statement:

select (1.0/2.0)*4.0;

Gives the same result, but doesn't need any casts.

Have a nice day,
--
Martijn van Oosterhout   <kleptog@svana.org>   http://svana.org/kleptog/
> From each according to his ability. To each according to his ability to litigate.

Attachment

pgsql-general by date:

Previous
From: Russell Smith
Date:
Subject: Re: ERROR: tuple concurrently updated
Next
From: Martijn van Oosterhout
Date:
Subject: Re: Simple stored procedure examples?