Attempt to compare string and number

I’m getting attempt to compare string and number error in if myTextButton.Text <= myTable.Number.

I just want to understand why sometimes I can compare string to numbers without conversion and sometimes not… (I know I can use tostring() or tonunber())

For example:

> n=1
> t="1"
> print(n==t)
  false

or

print( 5 * "5" ) --> 25

no errors…
But:

if myTextButton.Text <= myTable.Number

is giving that error…

What’s the logic for that?

2 Likes

It has to do with the way strings are represented, string are generally represented using ASCII. Thus they are compared by using the ASCII code for each character inside of the string, so this is why strings can only be compared with other strings, when using the >, <, <=, >=.

1 Like

I made a new test:

> n=1
> t="1"
> print(n==t) --> false
> print(n<=t) --> print(n<=t):1: attempt to compare number and string

So if I compare with == it’s ok, but <= I get the error…

Well this is because you’re checking if the string value is the same as the number value and it returns false cause they aren’t the same datatype. You can’t check if a string is bigger than a number.

2 Likes

Yes you can use the == operator, I mentioned the ones you cant use. When using the other operators it will not work because to check the difference it uses ASCII codes, which is a unique number for each character, adds them up, then compare the total for each string. For example if you print:

print( "abcdefg" < "z") --this will be true since the numerical code for z is much higher
2 Likes

hmm that soloution doesn’t work for me?
Script:

while 1 == 1 do
	wait(0.001)

	if script.Parent.Text < script.Parent.Money.Value then

		local MoneyNumber = script.Parent.Money.Value
		print("MONEY IS LAGGING BEHIND. IT NEEDS TO BE".. MoneyNumber.. " TO BE CORRECT")
		script.Parent.Text = script.Parent.Money.Value

	end




end

Hello ShadowMasterYT, Seems like you used Text to compare to a Number, this script should help you

while 1 == 1 do
wait(0.001)
local Number = tonumber(script.Parent.Text)
if Number < script.Parent.Money.Value then

	local MoneyNumber = script.Parent.Money.Value
	print("MONEY IS LAGGING BEHIND. IT NEEDS TO BE".. MoneyNumber.. " TO BE CORRECT")
	script.Parent.Text = script.Parent.Money.Value

end

end

never mind, if fixed it now :slight_smile:

I was a bit stupid and was using a script and not a local script

1 Like