Cast to integer

Started by Robert Osowieckiover 20 years ago5 messagesgeneral
Jump to latest
#1Robert Osowiecki
robson@cavern.pl

Hello!

Anyone could explain to me, why cast(3.33 to int) works (from float, I
suppose) but cast('3.33' to int) (from text) does not? And what if I
create a cast for that: is it possibly dangerous?

Regards,

Robert.

#2Sean Davis
sdavis2@mail.nih.gov
In reply to: Robert Osowiecki (#1)
Re: Cast to integer

On 10/5/05 9:08 AM, "Robert Osowiecki" <robson@cavern.pl> wrote:

Hello!

Anyone could explain to me, why cast(3.33 to int) works (from float, I
suppose) but cast('3.33' to int) (from text) does not? And what if I
create a cast for that: is it possibly dangerous?

How about:

sdavis=# select (('3.33')::float)::int;
int4
------
3
(1 row)

Sean

#3A. Kretschmer
akretschmer@despammed.com
In reply to: Robert Osowiecki (#1)
Re: Cast to integer

am 05.10.2005, um 15:08:33 +0200 mailte Robert Osowiecki folgendes:

Hello!

Anyone could explain to me, why cast(3.33 to int) works (from float, I
suppose) but cast('3.33' to int) (from text) does not? And what if I
create a cast for that: is it possibly dangerous?

test=# select '3.33'::float::int;
int4
------
3
(1 row)

Regards, Andreas
--
Andreas Kretschmer (Kontakt: siehe Header)
Heynitz: 035242/47212, D1: 0160/7141639
GnuPG-ID 0x3FFF606C http://wwwkeys.de.pgp.net
=== Schollglas Unternehmensgruppe ===

#4Tom Lane
tgl@sss.pgh.pa.us
In reply to: Robert Osowiecki (#1)
Re: Cast to integer

Robert Osowiecki <robson@cavern.pl> writes:

Anyone could explain to me, why cast(3.33 to int) works (from float, I
suppose) but cast('3.33' to int) (from text) does not?

The latter is not really a cast; it's an invocation of the int
datatype's input function.

regards, tom lane

#5Robert Osowiecki
robson@cavern.pl
In reply to: A. Kretschmer (#3)
Re: Cast to integer

A. Kretschmer wrote:

am 05.10.2005, um 15:08:33 +0200 mailte Robert Osowiecki folgendes:

Hello!

Anyone could explain to me, why cast(3.33 to int) works (from float, I
suppose) but cast('3.33' to int) (from text) does not? And what if I
create a cast for that: is it possibly dangerous?

test=# select '3.33'::float::int;
int4
------
3
(1 row)

Let me explain better. I encountered this problem when I tried to write
general unit-calculation (from kilograms to punds, for example) function
operating on any arithmetic datatype: with float and numeric it went all
ok, but failed with integer on "return $result" with error "invalid
input syntax for integer". My function internally operated on numeric
type. I wrote a wrap-around for integer, because I've been afraid, that
changing "text to integer" cast (or input function, whatever it is)
could damage something important.

R.