Re: Should casting to integer produce same result as trunc()

From: Alban Hertroys <haramrae(at)gmail(dot)com>
To: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
Cc: "Harvey, Allan AC" <HarveyA(at)onesteel(dot)com>, pgsql-general(at)postgresql(dot)org
Subject: Re: Should casting to integer produce same result as trunc()
Date: 2011-10-11 14:34:35
Message-ID: CAF-3MvNxkJ5REqp+Nqxtsd2LjQ=+gVGeb97F1BCeNhmpw1cBMQ@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On 11 October 2011 15:41, Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us> wrote:
> Alban Hertroys <haramrae(at)gmail(dot)com> writes:
>> On 11 Oct 2011, at 2:55, Harvey, Allan AC wrote:
>>> My simple understanding of trunc() and casting to an integer says that
>>> there is a bug here.
>
>> Which the type-cast should round to 4380103 and 4380104 respectively.
>> It doesn't:
>
> That's because a cast from float to int rounds, it doesn't truncate.
>
> regression=# select (4.7::float8)::int;
>  int4
> ------
>    5
> (1 row)

I figured it would be something like that. Is that how it's defined in
the SQL standard?

All other programming languages I've come to know truncate floats on
such casts (C, php, python, java, to name a few).
This is probably quite surprising to people used to these languages.

I agree that rounding is the right thing to do. We are probably just
too used to programming languages that truncate instead of round
because it was more convenient to implement it that way at the time.

--
If you can't see the forest for the trees,
Cut the trees and you'll see there is no forest.

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Sandro Santilli 2011-10-11 15:08:17 Re: [postgis-users] Query slow down, never completes
Previous Message Alban Hertroys 2011-10-11 14:26:47 Re: Global Variables?