Re: convert real to numeric.

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: "Peter J(dot) Holzer" <hjp-pgsql(at)hjp(dot)at>
Cc: pgsql-general(at)lists(dot)postgresql(dot)org
Subject: Re: convert real to numeric.
Date: 2018-10-18 22:58:13
Message-ID: 30660.1539903493@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

"Peter J. Holzer" <hjp-pgsql(at)hjp(dot)at> writes:
> On 2018-10-18 10:15:40 -0400, Tom Lane wrote:
>> You could ju-jitsu the system into duplicating that behavior by casting
>> to text (which invokes float4out) and then to numeric:

> I suggest casting first to float8 and then to numeric. The conversion
> from float4 to float8 is exact, and any rounding error introduced by the
> float8->numeric conversion is certainly much smaller than the
> uncertainty of the original float4 value.

I do not think that the OP will care for the results of that. The problem
is that now the output function will think that the result is worth
printing to 16 digits, and the last ten or so of those will be garbage.
As an example, even though the cited value happens to work nicely:

regression=# select '17637.75'::float4::float8;
float8
----------
17637.75
(1 row)

nearby ones don't:

regression=# select '17637.74'::float4::float8;
float8
-----------------
17637.740234375
(1 row)

Yeah, in some sense that's a valid representation of the stored float4,
but it likely has little to do with the originally presented value.

regards, tom lane

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Igor Korot 2018-10-19 04:49:12 What is the problem with this code?
Previous Message Steve Crawford 2018-10-18 22:36:07 Re: PGDG status and policy