Lua:从float转换为int

ddk*_*ddk 28 floating-point lua

尽管Lua没有区分浮点数和整数,但有些情况下你想要使用整数.如果你不能做一个类似C的演员或没有类似Python的东西,将数字转换为整数的最佳方法是什么int

例如,在计算数组的索引时

idx =位置/宽度

你怎么能确保idx有效的数组索引?我提出了一个使用的解决方案string.find,但也许有一种使用算法的方法显然会更快.我的解决方案

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
Run Code Online (Sandbox Code Playgroud)

小智 48

你可以用 math.floor(x)

来自Lua参考手册:

返回小于或等于x的最大整数.

  • 你可以通过抛出一些条来扩展这个答案以处理负数:`math.floor(math.abs(x))` (5认同)
  • 当然 - 但你需要随后将符号放回原处,否则你转换为 int 也是一个 abs() (3认同)

Cha*_*ong 9

Lua 5.3引入了一个新的运算符,称为floor division并表示为//

示例如下:

Lua 5.3.1版权所有(C)1994-2015 Lua.org,PUC-Rio

> 12 // 5

2

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


小智 6

@Hofstad是正确的,math.floor(Number x)建议消除小数点右边的位,你可能想要舍入.没有math.round,但它很简单math.floor(x + 0.5).你想要舍入的原因是浮动通常是近似的.例如,1可能是0.999999996

12.4 + 0.5 = 12.9,地板12

12.5 + 0.5 = 13,地板13

12.6 + 0.5 = 13.1,地板13

local round = function(a, prec)
    return math.floor(a + 0.5*prec) -- where prec is 10^n, starting at 0
end
Run Code Online (Sandbox Code Playgroud)