Code: Select all
function round(n, r)
local r = r or 0
return math.floor(n*10^r)/10^r
end
1.5 -> 1
-1.5 -> -2
The "classic round" rounds values away from zero when the decimal part is greater than or equal to 0.5, and towards zero when less than 0.5. That's how C++'s std::round does this. It returns values like this:
1.5 -> 2
-1.5 -> -2
Here's a snippet of most common round variations:
Code: Select all
-- "Classic round", rounds away from zero in halfway cases.
function round(num, idp)
local shift = idp and 10 ^ idp or 1
if num < 0 then
return math.ceil(num * shift - 0.5) / shift
end
return math.floor(num * shift + 0.5) / shift
end
function roundDown(num, idp)
local shift = idp and 10 ^ idp or 1
return math.floor(num * shift) / shift
end
function roundUp(num, idp)
local shift = idp and 10 ^ idp or 1
return math.ceil(num * shift) / shift
end
-- Truncates decimal part, leaving the rest of the number unchanged.
function trunc(num, idp)
local shift = idp and 10 ^ idp or 1
if num > 0 then
return math.floor(num * shift) / shift
end
return math.ceil(num * shift) / shift
end
function roundAwayFromZero(num, idp)
local shift = idp and 10 ^ idp or 1
if num > 0 then
return math.ceil(num * shift) / shift
end
return math.floor(num * shift) / shift
end