Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Way to set a string value to a number value?

I making code that will add two numbers that are put into a TextBox's Text property and return an answer into another TextBox. The code works perfectly, but if I type in a string and click the CalculateButton, it will give this error in the output: Players.Green_Lime2.PlayerGui.ScreenGui.CalculateButton.LocalScript:15: attempt to perform arithmetic (add) on string

Is there any way to block the strings and only accept numbers? The LocalScript is inside the CalculateButton. Here's the code:

print("Ready for calculating")
while true do
	wait(0.1)

local player = game.Players.LocalPlayer
local character = player.Character
local playergui = game.Players.LocalPlayer.PlayerGui
local calculatebutton = playergui.ScreenGui.CalculateButton
local textbox1 = playergui.ScreenGui.TextBox1
local textbox2 = playergui.ScreenGui.TextBox2
local answerbox = playergui.ScreenGui.AnswerBox
	
	calculatebutton.Activated:Connect(function(activated)
		if activated then
			answerbox.Text = textbox1.Text + textbox2.Text
			end
		end)
	end

2 answers

You would wanna make use of the tonumber function. It will convert strings to numbers (assuming those strings are made up of only numbers, or else it will return nil.)

answerbox.Text = tonumber(textbox1.Text) + tonumber(textbox2.Text)

An easy solution would be to use tonumber.

1 comment

0

I knew about the tonumber() function and I was using it wrongly in my code. Thanks for the help guys!

This discussion is preserved as it was. New answers, comments, and votes are closed.