[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Why is there no 'math.round'?
- From: Asko Kauppi <askok@...>
- Date: Wed, 23 Apr 2008 15:23:10 +0300
A rounding function would be a welcome addition to Lua's builtin
'math.*' framework.
math.round( x, 1 ) -- rounds to nearest integer
math.round( x, 10 ) -- rounds to nearest 10*N
Is there any particular reason why Lua lacks one?
I did find this: http://lua-users.org/wiki/SimpleRound . However,
ability to round to -say- 22.5 degrees or 500 meters would be useful.
I.e. giving the rounding as number, not as exponent. Rounding mode
could be an optional third parameters (nearest/towards zero/out of
zero/...).
--
-- num= round( num [,step_num=1] )
--
-- Round 'num' to nearest N*'step' (step can be any positive number,
i.e. 22.5)
--
local function round( v, step )
step= step or 1
assert( step > 0 )
return math.floor( (v+step/2) / step ) * step
end
I didn't use this yet, may have a bug.
-asko