Simple Round |
|
function round(num, idp) local mult = 10^(idp or 0) return math.floor(num * mult + 0.5) / mult end
Here is an alternative implementation:
function round2(num, idp) return tonumber(string.format("%." .. (idp or 0) .. "f", num)) end
Both are Lua 5.0 and 5.1 compatible.
Tests:
> function test(a, b) print(round(a,b), round2(a,b)) end > test(43245325.9995, 3) 43245326 43245325.999 > test(43245325.9994, 3) 43245325.999 43245325.999 > test(43245325.5543654) 43245326 43245326 > test(43245325.5543654, 3) 43245325.554 43245325.554 > test(43245325.5543654, 4) 43245325.5544 43245325.5544