| From: | Michael Fuhr <mike(at)fuhr(dot)org> | 
|---|---|
| To: | jeff sacksteder <jsacksteder(at)gmail(dot)com> | 
| Cc: | pgsql-general(at)postgresql(dot)org | 
| Subject: | Re: Implementing rounding rule in plpgsql | 
| Date: | 2005-11-20 09:24:20 | 
| Message-ID: | 20051120092420.GA32829@winnie.fuhr.org | 
| Views: | Whole Thread | Raw Message | Download mbox | Resend email | 
| Thread: | |
| Lists: | pgsql-general | 
On Sun, Nov 20, 2005 at 02:01:02AM -0500, jeff sacksteder wrote:
> Due to application requirements, I need to implement a rounding function
> that is independant of the baked-in rounding functionality. I'd prefer to do
> it in plpgsql for maximum portability.
> To do this, I'll need to sequentially walk through the digits of an
> arbritarily long floating-point number. I can't think of a good way to do
> this.
This wouldn't be a homework assignment, would it?  Anyway, maybe
this will give you some ideas:
CREATE FUNCTION myround(num double precision) RETURNS double precision AS $$
DECLARE
    textval  text := num;
    i        integer;
BEGIN
    FOR i IN 1 .. length(textval) LOOP
        RAISE INFO '[%] = %', i, substr(textval, i, 1);
    END LOOP;
    RETURN num;
END;
$$ LANGUAGE plpgsql IMMUTABLE STRICT;
test=> SELECT myround(1.23456789);
INFO:  [1] = 1
INFO:  [2] = .
INFO:  [3] = 2
INFO:  [4] = 3
INFO:  [5] = 4
INFO:  [6] = 5
INFO:  [7] = 6
INFO:  [8] = 7
INFO:  [9] = 8
INFO:  [10] = 9
  myround   
------------
 1.23456789
(1 row)
-- 
Michael Fuhr
| From | Date | Subject | |
|---|---|---|---|
| Next Message | Peter Eisentraut | 2005-11-20 11:09:10 | Re: Mambo (CMS) & PostgreSQL | 
| Previous Message | Justin Hawkins | 2005-11-20 08:49:58 | Re: Trouble with recursive trigger |