lua - 如何获取小数点以舍入一半

时间:2013-04-16 11:33:35

标签: lua rounding

我现在正在使用此功能进行舍入:

function round(val, decimal)
  if (decimal) then
    return math.floor( (val * 10^decimal) + 0.5) / (10^decimal)
  else
    return math.floor(val+0.5)
  end
end

除了当一个数字落在.5上,如5.5或1000.5或7.5,我需要它向上舍入而不是向上时,该功能才能完美运行。我必须对功能做些什么改变呢?

2 个答案:

答案 0 :(得分:7)

function round(val, decimal)
  local exp = decimal and 10^decimal or 1
  return math.ceil(val * exp - 0.5) / exp
end

答案 1 :(得分:2)

function round(val, decimal)
  local rndval = math.floor(val)
  local decval = val - rndval
  if decimal and decimal ~= 0 then
    decval = decval * 10 ^ decimal
    return rndval + (decval % 1 > 0.5 and math.ceil(decval) or math.floor(decval)) / 10 ^ decimal
  else
    return decval > 0.5 and rndval + 1 or rndval 
  end
end

我的懒惰。没有访问解释器来测试它,但它应该没问题。不知道,如果表现还不错......

编辑: 在LuaJIT上,对该函数的十亿次调用大约需要半秒钟。在简单的Lua上,每半秒钟就有一百万(Core i7 / 3610 mobile)。

相关问题