An archive of community.esquilo.io as of Saturday January 26, 2019.

Convert string to number

robertjensen

How can a string variable be converted to an integer or a float? I see the function "tointeger" in the squirrel reference, but this results in a message that the function does not exist. If I do something like x+0 where x="123", the "0" gets converted to a string and the result is "1230". I want to convert a string to a number so that I can do some math with it.

gwittie

Robert,
You can use the parseint function.
parseint(string, [base])

patrick

You should be able to use tointeger and parseint:

x <- "123"
print(x.tointeger() + 0 + "\n")
123
print(x.tointeger() + 10 + "\n")
133
print(x + 10 + "\n")
12310
print(parseint(x) + 10 + "\n")
133
print(parseint(x, 16) + 10 + "\n")
301
robertjensen

Thanks to both of you. I stupidly tried to make the string an argument of tointeger() instead of seeing that as a member function of the string class.

patrick

@robertjensen I've done the same thing before. That's why I included a specific example to clarify. I'm sure we're not the only ones .