Contents | Index | < Browse

ROUND -by Bernd Gollesch

Parse and round number to specified decimal precision...

This super efficient method of providing a function to round a number to a specified decimal precision, either to right or left of the decimal place, was submitted by Bernd Gollesch <bgollesch@sime.at> 31-May-2005 in the AmigaOS3.9 discussion group, "AmigaOS39@yahoogroups.com". Following is Bernd's code module; he wrote:

I found something to optimize, the "10**(-precision)" - just have to be done once.

/* parse and round number to specified decimal precision */

Round: PROCEDURE
PARSE ARG number, precision
multi = 10**(-precision)
IF precision < 0 THEN
number = TRUNC(number/multi + .5, 0) * multi
ELSE
number = TRUNC(number + .5*multi, precision)
RETURN number

This is an improvement on Bernd's first suggestion which was as follows:

Round:
procedure
/* parse and round number to specified decimal precision */

Number=arg(1)
precision=arg(2)

if precision < 0 then do
number = number / 10**(-precision)
number = trunc(number + .5, 0)
number = number * 10**(-precision)
end
else
number = trunc(number + .5 * 10**(-precision), precision)

RETURN number

*********************

Positiv number are precision right of the decimal point and negativ
numbers are for the left, eg:

rx round 76.556 -1 => 80
rx round 76.556 -2 => 100
rx round 76.556 -3 => 0

hth, Bernd