Lua: converting from float to int

后端 未结 4 1825
耶瑟儿~
耶瑟儿~ 2021-02-02 06:51

Even though Lua does not differentiate between floating point numbers and integers, there are some cases when you want to use integers. What is the best way to covert a number t

相关标签:
4条回答
  • 2021-02-02 07:22

    You could use math.floor(x)

    From the Lua Reference Manual:

    Returns the largest integer smaller than or equal to x.

    0 讨论(0)
  • 2021-02-02 07:27

    Lua 5.3 introduced a new operator, called floor division and denoted by //

    Example below:

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

    >12//5

    2

    More info can be found in the lua manual

    0 讨论(0)
  • 2021-02-02 07:32

    @Hofstad is correct with the math.floor(Number x) suggestion to eliminate the bits right of the decimal, you might want to round instead. There is no math.round, but it is as simple as math.floor(x + 0.5). The reason you want to round is because floats are usually approximate. For example, 1 could be 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

    local round = function(a, prec)
        return math.floor(a + 0.5*prec) -- where prec is 10^n, starting at 0
    end
    
    0 讨论(0)
  • 2021-02-02 07:43

    why not just use math.floor()? it would make the indices valid so long as the numerator and denominator are non-negative and in valid ranges.

    0 讨论(0)
提交回复
热议问题