Hi other developers,
I’ve been running into this problem where I don’t know how to extract a number out of a string.
Here is my code:
ClickForRebirthButton.Text = "$25"
if Cash.Value >= ClickForRebirthButton.Text then --// line here is broken
MinusCashEvent:FireServer()
RebirthEvent:FireServer()
end
You can use the %d character class to get the number of a string, and a + flag after the character class to get as many of the preceding character class as possible (in this case, the preceding character class is %d):
local str = "$25"
local numberFromString = string.match(str, "%d+")
local number = tonumber(numberFromString) --> "tonumber" converts a numerical string into a number
print(numberFromString) --> "25"
print(number) --> 25
Alternatively, if it will only ever have a known amount of characters (the dollar sign in this case) at the start, you could use string.sub rather than string.match. For example:
local str = "$19.43"
local number = tonumber(str:sub(2)) -- convert everything after the first character to a number
print(number) --> 19.43
-- supports decimals