Logo

Programming-Idioms

History of Idiom 81 > diff from v36 to v37

Edit summary for version 37 by Bug38:
New Lua implementation by user [Bug38]

Version 36

2016-12-06, 14:43:23

Version 37

2017-08-21, 12:16:03

Idiom #81 Round floating point number to integer

Declare integer y and initialize it with the rounded value of floating point number x .
Ties (when the fractional part of x is exactly .5) must be rounded up (to positive infinity).

Idiom #81 Round floating point number to integer

Declare integer y and initialize it with the rounded value of floating point number x .
Ties (when the fractional part of x is exactly .5) must be rounded up (to positive infinity).

Code
function round(float)
    local int, part = math.modf(float)
    if float == math.abs(float) and part >= .5 then return int+1    -- positive float
    elseif part <= -.5 then return int-1                            -- negative float
    end
    return int
end
Comments bubble
math.floor(x) will return the biggest integer below x
Doc URL
http://lua-users.org/wiki/MathLibraryTutorial