我用了两种方法将数字四舍五入到小数。第一个函数只是舍入数字:
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
为什么不简单地
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)
btw.
为什么你要把1乘以多次?
在对数字进行四舍五入时,有很多事情需要考虑。请研究一下如何处理特殊情况。