How do I detect if the text is a numerical value?

im making a gui that changes the workspace gravity. the player enters something in the textbox and the workspace gravity is equal to the text in the textbox (for example if i enter 196 then the gravity is now 196)

but people could just enter random characters. so i want to detect if the text is a numerical value that could actually change the gravity

so how do i do this?

2 Likes
local function isNumber(x: string): boolean
	return tonumber(x) ~= nil
end

if isNumber("5.5") then
	print("5.5 is a number!")
end
if isNumber("25x") then
	print("25x is a number!") --should not print
end

Basically if the function tonumber returns a number instead of nil, it means that the string input was numeric.

2 Likes
    local newGravityValue = tonumber(TextBox.Text)
    if newGravityValue then
        -- what is inserted is fully a number and you change the gravity value
    else
        -- did not pass the tonumber check thus meaning it's not fully a numerical value that was inserted 
    end

documentation on tonumber

2 Likes

Or if you want to be fancy:

workspace.Gravity = tonumber(TextBox.Text) or workspace.Gravity
2 Likes

Here is my code

local Button = script.Parent
local TextBox = script.Parent.Parent.TextBox

script.Parent.MouseButton1Click:Connect(function()
	
	workspace.Gravity = tonumber(TextBox.Text) or workspace.Gravity
	
	script.Parent.Sound:Play()
	
end)

im trying to make it so that the sound does not play if the value is not a number so how can i fix my code to do that

1 Like

also i am a new scripter so thanks for posting the documentation ill look over that

if not tonumber(TextBox.Text) then return end
workspace.Gravity = tonumber(TextBox.Text)
script.Parent.Sound:Play()

You can also use typeof() to find out if a passed value is a number
like

local A = "A"
local B = 1

print(typeof(A))
print(typeof(B))

console

string
number

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.