How to check if a string is a number?

Basically, I have an event that fires whenever a player presses a button. I was wondering, how would I check if the key that the player presses is a number, or a letter? Thanks :slight_smile:

if tonumber(String) then
    print("a number")
else
    print("not a number")
end
1 Like

if its a number it would be

if [value] >= 0 then
[what ev]
end

tonumber(string)

so I would do

if tonumber(keypressed) >= 0 then

end

?

no that wouldn’t work, if it is a letter it will error because nil can’t be compared with a number

if tonumber(keypressed) then
    print("this will run if keypressed is a number and not a letter")
end
3 Likes
if string.find(Key, "%d") then
    -- Key contains / is a number
end

Try this out.

string.find lets you search a string for any text. if the string doesn’t contain the text string.find will return nil, and if it does it’ll return the amount of times the text appears in the string (iirc). "%d" is a string pattern that represents any number. Searching a string for "%d" is like searching a string for every number.

Edit: If you’re getting the key from UserInputService then the key will be an Enum and not a string, so this method won’t work. Also just realized you could just use tonumber instead, like D0RYU suggested.

5 Likes

Not necessarily since the number could be a negative number.

And this will error if it is a letter.

1 Like

It’s a key pressed thing and you can’t type negative numbers on a keyboard without pressing multiple keys.

Sorry, I thought it was a TextBox but anyway

1 Like

If it possible to put if statements in a pcall? If so you could do what @nicknickphoenix said in a pcall. If it errors, its a letter, if not its a number.

You might be able to use the type() function for this too.

1 Like

I guess it’s:

if type(tonumber(key)) == "number" then

end
1 Like