lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


2016-08-04 23:24 GMT+02:00 Dirk Laurie <dirk.laurie@gmail.com>:
> 2016-08-04 20:48 GMT+02:00 Egor Skriptunoff <egor.skriptunoff@gmail.com>:
>
>> Your function will return wrong result for round(math.maxinteger + 0.75)
>> on Lua built with 32-bit integer as LUA_INTEGER and double as
>> LUA_NUMBER.
>
>> Can you fix your function so it would give correct result for any
>> combination of LUA_INTEGER and LUA_NUMBER?
>
> How is this?
>
> function(x)
>   local floor, frac = math.modf(x)
>   return (frac<0.5 or frac==0.5 and floor%2==0) and floor
>       or math.ceil(x)
> end

Wrong for negative numbers :-(

round = function(x)
  local floor = math.floor(x)
  local frac = x-floor
  return (frac<0.5 or frac==0.5 and floor%2==0) and floor
      or math.ceil(x)
end