[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Rounding a number to integer
- From: Roberto Ierusalimschy <roberto@...>
- Date: Fri, 5 Aug 2016 15:39:59 -0300
> > Another try :-)
> >
> > -- unbiased rounding
> > function round (x)
> > if math.floor(x) == x then return x
> > else
> > return math.floor((x % 2.0 == 0.5) and x or x + 0.5)
> > end
> > end
> >
>
> round(0.0) gives float result 0.0 instead of integer 0
Is this in the "rules"? :-) If so, it seems easy to fix:
function round (x)
local fx = math.floor(x)
if (fx == x) or (x % 2.0 == 0.5) then
return fx
else
return math.floor(x + 0.5)
end
end
-- Roberto