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

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Alban Hertroys <haramrae(at)gmail(dot)com>
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 15:52:40
Message-ID: 1656.1318348360@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Alban Hertroys <haramrae(at)gmail(dot)com> writes:
> On 11 October 2011 15:41, Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us> wrote:
>> That's because a cast from float to int rounds, it doesn't truncate.

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

SQL99 says

Whenever an exact or approximate numeric value is assigned to
an exact numeric value site, an approximation of its value that
preserves leading significant digits after rounding or truncating
is represented in the declared type of the target. The value is
converted to have the precision and scale of the target. The choice
of whether to truncate or round is implementation-defined.

An approximation obtained by truncation of a numeric value N for an
<exact numeric type> T is a value V in T such that N is not closer
to zero than is V and there is no value in T between V and N.

An approximation obtained by rounding of a numeric value N for an
<exact numeric type> T is a value V in T such that the absolute
value of the difference between N and the numeric value of V is
not greater than half the absolute value of the difference between
two successive numeric values in T. If there is more than one such
value V, then it is implementation-defined which one is taken.

or in short, "you can do it in any reasonable fashion". It looks like
our code for this has used rint() since the day it was put in,
http://git.postgresql.org/gitweb/?p=postgresql.git;a=commitdiff;h=64d9b508939fb15d72fdfa825ee8938506764d66

regards, tom lane

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Bruce Momjian 2011-10-11 18:52:29 Re: Logging queries cancelled due to replication timeouts
Previous Message Sandro Santilli 2011-10-11 15:16:42 Re: [postgis-users] Query slow down, never completes