Simple Round

lua-users home
wiki

The following function rounds a number to the given number of decimal places.

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

Note: The first function will misbehave if idp is negative, so this version might be more robust (Robert Jay Gould)


Actually i wanted it to round to 100s, so the negative cases are very useful and ok mathematically (no error there):

round(1023.4345, -2) = 1000
round(1023.4345, 2) = 1023.43
(Tom P.)
function round(num, idp)
  if idp and idp>0 then
    local mult = 10^idp
    return math.floor(num * mult + 0.5) / mult
  end
  return math.floor(num + 0.5)
end


function round(num) return math.floor(num+.5) end
-- Rob

Might have unintended result for -.5? Please see below.

-- Henning


Round towards zero
    function round(num) 
        if num >= 0 then return math.floor(num+.5) 
        else return math.ceil(num-.5) end
    end

Note that math.ceil(num-.5) ~= math.floor(num+.5) e.g. for -.5 with math.ceil(num-.5) == -1 math.floor(num+.5) == 0

Samples: 1.1 -> 1, 1 -> 1, 0.9 -> 1, 0.5 -> 1, 0.1 -> 0, 0 -> 0, -0.1 -> 0, -0.4 -> 0, -0.5 -> -1, -0.6 -> -1, -0.9 -> -1, -1: -1, -1.1: -1

-- Henning


function round(num)
    under = math.floor(num)
    upper = math.floor(num) + 1
    underV = -(under - num)
    upperV = upper - num
    if (upperV > underV) then
        return under
    else
        return upper
    end
end

RecentChanges · preferences
edit · history
Last edited October 26, 2010 11:28 pm GMT (diff)