Skip to content

Instantly share code, notes, and snippets.

@walterlua
Created May 18, 2011 07:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save walterlua/978154 to your computer and use it in GitHub Desktop.
Save walterlua/978154 to your computer and use it in GitHub Desktop.
Implementation of JavaScript math.round() in Lua. Also, adds the function to Lua's math library
-- math.round( num ) rounds num to the nearest integer following the
-- same rules as the JavaScript version, i.e. if the fractional
-- portion of number is .5 or greater, the argument is rounded to the
-- next higher integer. If the fractional portion of number is less
-- than .5, the argument is rounded to the next lower integer.
math.round = function(num)
return math.floor(num+.5)
end
-- Example Usage:
local function testRound( num )
print( num, math.round( num ) )
end
testRound( 0.1 ) -- Output: 0.1 0
testRound( 0.5 ) -- Output: 0.5 1
testRound( 8.9 ) -- Output: 8.9 9
testRound( -0.1 ) -- Output: -0.1 0
testRound( -0.5 ) -- Output: -0.5 0
testRound( -8.9 ) -- Output: -8.9 -9
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment