tonumber

Converts a string (of the given base) to a number

Prototype

n = tonumber (n, base)

Description

Converts n to a number using the optional base (default 10). Base can be from 2 to 36. For bases > 10 the letters a-z (not case sensitive) represent the digits. (eg. F is 15).
For decimal numbers you can supply fractions and exponents. Others should be unsigned.
Returns nil if the number cannot be converted.

print (tonumber ("100100", 2)) --> 36
print (tonumber ("1e5")) --> 100000
print (tonumber ("1EF", 16)) --> 495 
You can use tonumber as a quick check if a variable contains something convertable to a number.

print (tonumber ("abc")) --> nil
print (tonumber ("-43")) --> -43
print (tonumber (-43))   --> -43
To see if the variable actually is already a number type, use the "type" function:

print (type ("-43")) --> string
print (type (-43))   --> number
See also bit.tonumber which will handle larger numbers.

Lua functions

Topics