Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Lua

Idiom #81 Round floating point number to integer

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

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

math.floor(x) will return the biggest integer below x
function round(float)
    return math.floor(float + .5)
end
Y : constant Integer := Integer (Float'Rounding (X));

New implementation...