Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
2

How can I convert numbers in a String to Number Values?

Asked by 10 years ago

I want users to be able to type numbers into a TextBox, and then use the Inputted numbers as number values rather than string values. How can I convert Strings into Numbers?

What I have now may work, but I realized that if the User inputs a non-numeric character the script will attempt to perform mathematics on a letter.

What I have so far:

if player.Coins.Value >= script.Parent.Parent.CoinConvert.Text then
        if script.Parent.Parent.CoinConvert.Text/25 == 1 then
            player.Coins.Value = player.Coins.Value - script.Parent.Parent.CoinConvert.Text
            player.Points.Value = player.Points.Value + (script.Parent.Parent.CoinConverter.Text/25)
        end
end
--This isn't the full script, just a portion of it.
--CoinConvert is the name of the TextBox.

Also, how can I check if the Text of a TextBox is changed? I would assume that the .Changed event doesn't work, as it only works on Values.

1 answer

Log in to vote
3
Answered by 10 years ago

Use the tonumber function.

tonumber() accepts one argument, the string you want to convert, and returns the number value. However, it will return nil if you don't give a string that is solely just numerals.

For example-

x = "Hello"

y = tonumber(x) + 1

print(y)

Would return an error when you try to compare tonumber(x) to 1, because tonumber(x) is nil, and you can't compare nil with a value.

With the correct usage:

x = "123"

y = tonumber(x) + 1

print(y)

... would print 124, as we wrote in the script.

__________________________________________________

I hope you found this useful!

(also, you can do the exact opposite with the tostring function, which turns any value other than nil into a string)

0
Thanks! SlickPwner 534 — 10y
Ad

Answer this question