Re: Rounding

From: Joe Conway <mail(at)joeconway(dot)com>
To: Chris Boget <chris(at)wild(dot)net>
Cc: PGSql Novice <pgsql-novice(at)postgresql(dot)org>
Subject: Re: Rounding
Date: 2003-10-03 16:24:11
Message-ID: 3F7DA2AB.80300@joeconway.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-novice

Chris Boget wrote:
> Is there a way, internal in PG, that you can round to the
> nearest half decimal (rounded up or down)? ie, I want to
> round 97.37 to 97.5 or 97.81 to 98.
> The closest thing I could see in the docs would take the
> 97.33 turning it into 97.4 and 97.81 to 97.8. Is there some-
> thing I am missing?
>

I don't know of a built in way to "round to the nearest half increment",
which it seems you want to do. You could always write a function for it.
e.g.:

create or replace function nearesthalf(float8)
returns float8 as '
select case
when ($1 - floor($1)) <= 0.25 then floor($1)
when ($1 - floor($1)) > 0.75 then ceil($1)
else (ceil($1) + floor($1)) / 2
end
' language sql;

regression=# select nearesthalf(97.17);
nearesthalf
-------------
97
(1 row)

regression=# select nearesthalf(97.37);
nearesthalf
-------------
97.5
(1 row)

regression=# select nearesthalf(97.67);
nearesthalf
-------------
97.5
(1 row)

regression=# select nearesthalf(97.77);
nearesthalf
-------------
98
(1 row)

Is this what you were looking for?

Joe

In response to

  • Rounding at 2003-10-03 15:26:11 from Chris Boget

Browse pgsql-novice by date

  From Date Subject
Next Message Joe Conway 2003-10-03 16:29:26 Re: Adding PL languages laster
Previous Message Tom Lane 2003-10-03 16:24:08 Re: Rounding