Banzivar
Banzivar

Reputation: 21

How can "1" be greater than 50?

I'm baffled by the following and hope I'm about to learn something. When I run the following code:

<%
Response.Write "ss = ""1""<br/>"
ss = "1"
Response.Write "ii = 50<br/>"
ii = 50
Response.Write "ss >= ii "
If ss >= ii Then Response.Write "True?" Else Response.Write "False"
Response.Write "<br/>""1"" >= 50 "
If "1" >= 50 Then Response.Write "True" Else Response.Write "False"
%>

It writes:

ss = "1"
ii = 50
ss >= ii True?
"1" >= 50 False

MSDN says If operands are One numeric and one String Comparison is The String is converted to a Double and numeric comparison is performed. If the String cannot be converted to Double, an InvalidCastException is thrown.

I'm using ASP version 5.8, build number 18525.

I don't require a workaround as I have one but I was wondering if there is a reason for this as it's an easy mistake to make.

Edit: Chosen correct answer has a comment with a further link to detail of the difference between the 2 comparisons.

Upvotes: 1

Views: 191

Answers (1)

TZHX
TZHX

Reputation: 5387

You are looking at documentation for .NET, while using VBScript (which is not a .NET language). To quote the VBScript language reference, then when comparing a string to a number,

The numeric expression is less than the string expression.

Source

The reason your second if evaluates to False is because of the way VBScript treats variables and literals differently in comparisons. Because you have a literal number, the literal string is being converted as you initially expected.

Upvotes: 7

Related Questions