lua-users home
lua-l archive

Re: Rounding a number to integer

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


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

AltStyle によって変換されたページ (->オリジナル) /