Reputation: 3214
I'm using this function to round currently:
function round(val, decimal)
if (decimal) then
return math.floor( (val * 10^decimal) + 0.5) / (10^decimal)
else
return math.floor(val+0.5)
end
end
That function works perfectly except that when a number lands on .5 like 5.5 or 1000.5 or 7.5 I need it to round down instead of up. What changes would I have to make to the function to make that happen?
Upvotes: 3
Views: 4883
Reputation: 23727
function round(val, decimal)
local exp = decimal and 10^decimal or 1
return math.ceil(val * exp - 0.5) / exp
end
Upvotes: 7
Reputation: 5525
function round(val, decimal)
local rndval = math.floor(val)
local decval = val - rndval
if decimal and decimal ~= 0 then
decval = decval * 10 ^ decimal
return rndval + (decval % 1 > 0.5 and math.ceil(decval) or math.floor(decval)) / 10 ^ decimal
else
return decval > 0.5 and rndval + 1 or rndval
end
end
My lazy take. Don't have access to the interpreter to test it, but it should be fine. Don't know, if performance is ok though...
EDIT: On LuaJIT one billion calls to the function takes about half a second. On plain Lua it's one million per half a second (Core i7/3610 mobile).
Upvotes: 2