Re: dividing integers not producing decimal fractions

From: Martijn van Oosterhout <kleptog(at)svana(dot)org>
To: rloefgren(at)forethought(dot)net
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: dividing integers not producing decimal fractions
Date: 2006-11-05 10:07:31
Message-ID: 20061105100731.GB3979@svana.org
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Fri, Nov 03, 2006 at 02:03:59PM -0800, rloefgren(at)forethought(dot)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(at)svana(dot)org> http://svana.org/kleptog/
> From each according to his ability. To each according to his ability to litigate.

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Martijn van Oosterhout 2006-11-05 10:12:36 Re: Simple stored procedure examples?
Previous Message Russell Smith 2006-11-05 10:05:56 Re: ERROR: tuple concurrently updated