哪个Lua函数更好用?

时间:2019-10-29 08:47:57

标签: performance math lua

我采用了两种方法将数字四舍五入为小数。第一个函数只是四舍五入数字:

function round(num)
    local under = math.floor(num)
    local over = math.floor(num) + 1
    local underV = -(under - num)
    local overV = over - num
    if overV > underV then
        return under
    else
        return over
    end
end

接下来的两个函数使用此函数将数字四舍五入为小数:

function roundf(num, dec)
    return round(num * (1 * dec)) / (1 * dec)
end

function roundf_alt(num, dec)
    local r = math.exp(1 * math.log(dec));
    return round(r * num) / r;
end

1 个答案:

答案 0 :(得分:1)

为什么不简单

function round(num)
  return num >= 0 and math.floor(num+0.5) or math.ceil(num-0.5)
end

您可以直接使用math.floor(num) + 1来代替math.ceil(num)

为什么要乘以1倍?

四舍五入数字时要考虑很多事情。请对如何处理特殊情况做一些研究。

相关问题