Re: rounding problem
These are the rounding functions that I use:
global type nonnegative_int (object x)
if integer(x) then
return x >= 0
end if
return 0 -- FALSE
end type
global function round_half_even (object x, nonnegative_int digits)
-- rounding according to the IEEE standard
-- in: x : (sequence of) number(s) to round
-- digits: desired number of decimal places
atom p, ret
if atom(x) then
p = power(10, digits)
ret = floor(x*p + 0.5)
if remainder(ret, 2) then
ret -= 1
end if
return ret/p
end if
for i = 1 to length(x) do
x[i] = round_half_even(x[i], digits)
end for
return x
end function
global function round_half_up (object x, nonnegative_int digits)
-- "commercial rounding"
-- in: x : (sequence of) number(s) to round
-- digits: desired number of decimal places
atom p
if atom(x) then
p = power(10, digits)
if x >= 0 then
return floor( x*p + 0.5)/p
else
return -floor(-x*p + 0.5)/p
end if
end if
for i = 1 to length(x) do
x[i] = round_half_up(x[i], digits)
end for
return x
end function
-- Demo
? round_half_even( 2.65, 1)
? round_half_up ( 2.65, 1)
? round_half_even( 2.75, 1)
? round_half_up ( 2.75, 1)
puts(1, "\n")
? round_half_even(-2.65, 1)
? round_half_up (-2.65, 1)
? round_half_even(-2.75, 1)
? round_half_up (-2.75, 1)
Regards,
Juergen
|
Not Categorized, Please Help
|
|