[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Rounding a number to integer
- From: Dirk Laurie <dirk.laurie@...>
- Date: Wed, 3 Aug 2016 20:09:17 +0200
2016-08-03 19:30 GMT+02:00 Egor Skriptunoff <egor.skriptunoff@gmail.com>:
> On Sun, Jul 31, 2016 at 9:33 PM, Roberto Ierusalimschy
> <roberto@inf.puc-rio.br> wrote:
>>
>> What about this one?
>>
>> function round (x)
>> return math.floor((x % 2.0 == 0.5) and x or x + 0.5)
>> end
>
>
>> (2^52+1)|0, round(2^52+1)
> 4503599627370497 4503599627370498
function round(x)
local ans = math.floor(x)
local err = x-ans
if err<0.5 then return ans
elseif err>0.5 then return ans+1
elseif ans%2==0 then return ans
else return ans+1
end
end