首页 > 解决方案 > 哪个 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

标签: performancemathlua

解决方案


为什么不简单

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?

四舍五入时需要考虑很多事情。请研究如何处理特殊情况。


推荐阅读