The math.tointeger() function attempts to convert a given value to an integer. If the value is convertible to an integer, it returns that integer; otherwise, it returns nil.
Syntax
math.tointeger(x)
Parameters
- x: A number or value that you want to convert to an integer.
Return Value
- If
xcan be converted to an integer, it returns the integer value. - If
xcannot be converted to an integer, it returnsnil.
Description
The math.tointeger function checks whether the provided value x can be represented as an integer. If it can, the function returns the integer representation; if it cannot (e.g., if x is a non-integer number, NaN, or is outside the range of integers), it returns nil.
Examples
Basic usage of math.tointeger()
print(math.tointeger(42)) -- Output: 42
print(math.tointeger(3.14)) -- Output: nil (not an integer)
print(math.tointeger(0)) -- Output: 0
print(math.tointeger(-100)) -- Output: -100
print(math.tointeger(1e6)) -- Output: 1000000
print(math.tointeger(math.huge)) -- Output: nil (not an integer)
print(math.tointeger(5.0)) -- Output: 5 (5.0 is convertible to 5)
print(math.tointeger("42")) -- Output: nil (string is not convertible)
See also
math.floor(): Returns the largest integer less than or equal to a number.math.ceil(): Returns the smallest integer greater than or equal to a number.math.modf(): Returns the integer part and the fractional part of a number.