关于浮点数:Lua:从float转换为int

Lua: converting from float to int

即使Lua不能区分浮点数和整数,但是在某些情况下,您仍想使用整数。如果您无法进行类似C的转换或没有类似Python的int之类的东西,那么将数字转换为整数的最佳方法是什么?

例如,当为

中的数组计算索引时

idx = position / width

如何确保idx是有效的数组索引?我想出了一个使用string.find的解决方案,但是也许有一种使用算术的方法显然会更快。我的解决方案:

1
2
3
4
5
6
7
8
9
function toint(n)
    local s = tostring(n)
    local i, j = s:find('%.')
    if i then
        return tonumber(s:sub(1, i-1))
    else
        return n
    end
end

您可以使用math.floor(x)

来自Lua参考手册:

Returns the largest integer smaller than or equal to x.


Lua 5.3引入了一个名为floor division的新运算符,并用//

表示

以下示例:

Lua 5.3.1 Copyright (C) 1994-2015 Lua.org, PUC-Rio

>12//5

2

更多信息可以在lua手册中找到


@Hofstad与math.floor(Number x)建议正确,以消除小数点右边的位,您可能需要四舍五入。没有math.round,但是和math.floor(x + 0.5)一样简单。您想取整的原因是因为浮点数通常是近似值。例如,1可能是0.999999996

12.4 + 0.5 = 12.9, floored 12

12.5 + 0.5 = 13, floored 13

12.6 + 0.5 = 13.1, floored 13

1
2
3
local round = function(a, prec)
    return math.floor(a + 0.5*prec) -- where prec is 10^n, starting at 0
end

为什么不只使用math.floor()?只要分子和分母为非负数且在有效范围内,它将使索引有效。