lua-users home
lua-l archive

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


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

Yes, that's correct (but cumbersome).
Don't you like codegolf?  :-)

function round(x)
   local y = math.ceil(x - 0.5)
   return x - y + y/2%1 < 1 and y or math.ceil(x)
end