Created
May 18, 2011 07:45
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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