lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

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: . 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

I didn't use this yet, may have a bug.