Struggling to convert string into number

Hello developers, I’m currently looking for a way to use tonumber() on a string, with both letters and numbers. The issue is that, when I use tonumber() it returns nil, and I have tried searching for many posts about string manip, tried many and they have failed.

For example:

local s = "https://www.roblox.com/catalog/232525252"
print(tonumber(s))

(I want it to print 232525252 only)

The string must be only the number otherwise it’ll try to convert everything, but it realizes that, for instance, the letter h isn’t a valid number, thus will return nil, here what you can do:

local s = "232525252"
print(tonumber(s))

If you can’t directly change it like above, you can simply do this:

local s = "https://www.roblox.com/catalog/232525252"
s = s:gsub("https://www.roblox.com/catalog/", "") --Remove this piece from the string
print(tonumber(s))

This prints nil. I’m trying to format string so it only has numbers, nothing else. Therefore I can correctly use tonumber()

Sorry, there was a small mistake, I fixed it now.

I believe you want to do this:

local s = "https://www.roblox.com/catalog/232525252"
local num = tonumber(string.match(s, "%d+"))

print(num)

This is better then @SirTobiii’s method because if the base URL changes this method will still work (unlike tobiii’s)

2 Likes

You’ll be looking for just the digits? Search for a string pattern instead.

local s = 'https://www.roblox.com/catalog/232525252'

print(string.match(s, '%d+'))
1 Like