The tonumber()
method in Lua converts the value provided to it into a number. If this argument is a number or a convertible string, the tonumber()
function returns the converted number. If it is not a number or a convertible string, it will return nil
.
tonumber(targetValue)
targetValue
: This is the value that will be converted to a number value. It can be of any data type.The function returns the converted number value.
In the code snippet below, we convert some values to a number value using the tonumber()
function:
mynumber1 = 231.23mynumber2 = 400mystring1 = " This is a noncontible string"mystring2 = "4839"nilvlaue = niltableValue = {2,3,5,"49"};--will return the original numberprint(tonumber(mynumber1))print(tonumber(mynumber2))--will return nil because this is inconvertible stringprint(tonumber(mystring1))--will return the number equivalent of this stringprint(tonumber(mystring2))--returns nill, because data type nil can't convertprint(tonumber(nilvlaue))--converting the whole of the table will failprint(tonumber(tableValue))--converting a particular convertible element worksprint(tonumber(tableValue[4]))
tonumber()
function.tonumber()
method to convert a non-convertible string to a number. This returns nil
.tonumber()
method to convert a convertible string to a number. It returns the converted value, which is now a number.nil
and table
values.table
value declared earlier and convert it using the tonumber()
function.