From: Tom Lane <tgl@sss.pgh.pa.us>
To: Demitri Muna <postgresql@demitri.com>
Cc: pgsql-general@lists.postgresql.org
Subject: Re: Getting a primitive numeric value from "DatumGetNumeric"?
Date: Tue, 20 Feb 2018 22:54:41 -0500
Message-ID: <21871.1519185281@sss.pgh.pa.us> (raw)
In-Reply-To: <A3E2B8BE-7EE5-4555-90D8-09C832F7B558@demitri.com>
References: <A3E2B8BE-7EE5-4555-90D8-09C832F7B558@demitri.com>
Demitri Muna <postgresql@demitri.com> writes:
> I’m writing a C extension for PostgreSQL. One possible input datatype for my function is a numeric array, e.g. ARRAY[[1.5,2.5],[3.5,4.5]]. I can use “DatumGetNumeric” to extract a “Numeric” data type from the data, but at some point I need to convert this to a number (e.g. double) so that I can do mathy things with it. How does one convert a “Numeric” to, say, a double?
If you want to work with doubles, why don't you declare the function as
taking doubles?
> I have a workaround in that I can pass this to my function:
> ARRAY[[1.5,2.5],[3.5,4.5]]::float8[]
> but I’d rather have the code do that instead of bothering the user to remember that.
Well, the implicit coercions work in your favor in this particular case.
You can just do, eg,
regression=# create function foo(float8[]) returns float8 as
regression-# 'select $1[1]' language sql;
CREATE FUNCTION
regression=# select foo(array[1.1,1.2]);
foo
-----
1.1
(1 row)
or to emphasize that it is doing a conversion:
regression=# select foo(array[1.1,1.2]::numeric[]);
foo
-----
1.1
(1 row)
regards, tom lane
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients from your mail client; the link fills in
the headers below: reply via email
Some clients, webmail especially, drop In-Reply-To and References from
a link, and the reply then starts a new thread: use the mbox below.
To: pgsql-general@postgresql.org
Cc: tgl@sss.pgh.pa.us, postgresql@demitri.com
Subject: Re: Getting a primitive numeric value from "DatumGetNumeric"?
In-Reply-To: <21871.1519185281@sss.pgh.pa.us>
References: <A3E2B8BE-7EE5-4555-90D8-09C832F7B558@demitri.com> <21871.1519185281@sss.pgh.pa.us>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox