Reputation: 10400
I have the following script
document.write("12" < "2");
which returns true. Any reason why? The documentation says that javascript compares strings numerically but, I don't see how "12" is less than "2".
Upvotes: 4
Views: 2811
Reputation: 8249
I believe it is doing a lexicographic comparison - the first char in string one is '1', which is less than the first char of string two, which is '2'. More about Lexicographic order here: http://en.wikipedia.org/wiki/Lexicographical_order
Upvotes: 5
Reputation: 253506
This is because the first character of "12"
is 1
, which comes before "2"
; and JavaScript string comparison is lexically/alphabetically, rather than numerically. Though it appears partially numeric, since 1
is sorted ahead of 2
.
You can, however, simply compare the numbers as numbers:
document.write(parseFloat("12") < parseFloat("2"));
Upvotes: 3
Reputation: 944534
JavaScript compares strings character by character until one of the characters is different.
1 is less than 2 so it stops comparing after the first character.
Upvotes: 10