Re: Casting Varchar to Numeric

From: Karel Zak <zakkr(at)zf(dot)jcu(dot)cz>
To: Jan Wieck <janwieck(at)yahoo(dot)com>
Cc: Martijn van Oosterhout <kleptog(at)svana(dot)org>, Andy Marden <amarden(at)usa(dot)net>, pgsql-general(at)postgresql(dot)org
Subject: Re: Casting Varchar to Numeric
Date: 2001-12-06 09:22:23
Message-ID: 20011206102223.C23044@zf.jcu.cz
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Wed, Dec 05, 2001 at 05:09:48PM -0500, Jan Wieck wrote:
> Martijn van Oosterhout wrote:
> > On Wed, Nov 28, 2001 at 04:30:00PM -0000, Andy Marden wrote:
> > > Well, I've finally sorted it out and can now convert text/varchar fields
> > > into numeric I cannot BELIEVE I've had to resort to such things.
> > >
> > > I've changed all my varchar fields to text and then applied this to them
> > > (column name is 'litre_amount'):
> >
> > <snip ugly conversion method>
> >
> > Does this work?
> >
> > select litre_amount::float::numeric;
>
> Maybe it works, but with the step through float you loose
> precision. In the old days where the type input/output
> functions wheren't protected, one was able to use
>
> select numeric_in(textout(litre_amount)) from ...
>
> Well, some thought it'd not be such a good idea to let end
> users muck around with C string pointers, and IIRC I was one
> of them.
>
> But there are still the internal casting capabilities of
> PL/pgSQL. What about
>
> CREATE FUNCTION to_numeric ( text ) RETURNS numeric AS '
> BEGIN
> RETURN $1;
> END;' LANGUAGE 'plpgsql';
>
> Maybe this function is far too overcomplicated and someone
> might enhance the algorithm :-)

We already have to_number() that cast from string to numeric...

test=# SELECT to_number('1234.5678', '9999999999999999.999999999999999999');
to_number
-----------
1234.5678
(1 row)

... small problem is that you must set expectant format of string.

http://www.postgresql.org/idocs/index.php?functions-formatting.html

Karel

--
Karel Zak <zakkr(at)zf(dot)jcu(dot)cz>
http://home.zf.jcu.cz/~zakkr/

C, PostgreSQL, PHP, WWW, http://docs.linux.cz, http://mape.jcu.cz

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Denis Gasparin 2001-12-06 09:48:54 Query to fetch all lo and oid tables/columns in a database
Previous Message Denis Gasparin 2001-12-06 08:02:48 Re: PostgreSQL BLOB