Reputation: 1
I've tried to compare qml string "10" biggest than "9", but console.log sent me false
console.log("10" > "9");
console output false
qml: false
Explain to me why this doesn't work
Upvotes: 0
Views: 2391
Reputation: 1199
You can use this workaround:
console.log("10"*1 > "9"*1); // true
If you are going to use parseInt take care about the radix parameter. In previus example there is no radix parameter, so the interpreter will fall back to the default behaviour, which typically treats numbers as decimal, unless they start with a zero (octal) or 0x (hexadecimal)
Upvotes: 0
Reputation: 4869
Explain to me why this doesn't work
This is really a JavaScript question because that is the language used by QML processor. You're comparing strings, not numbers. Here's a good explanation of string (and in general) comparison in JavaScript.
I will quote the relevant part and present my own example:
To see whether a string is greater than another, JavaScript uses the so-called “dictionary” or “lexicographical” order. In other words, strings are compared letter-by-letter.
The algorithm to compare two strings is simple:
- Compare the first character of both strings.
- If the first character from the first string is greater (or less) than the other string’s, then the first string is greater (or less) than the second. We’re done.
- Otherwise, if both strings’ first characters are the same, compare the second characters the same way.
- Repeat until the end of either string.
- If both strings end at the same length, then they are equal. Otherwise, the longer string is greater.
console.log("10" > "9"); // false, first character is smaller
console.log("9" > "8"); // true, first character is larger
console.log("9" > "08"); // true, first char. is larger
console.log("10" > "09"); // true, first char. is larger
console.log("100" > "11"); // false, second char. is smaller
Upvotes: 2
Reputation: 4198
If you know the strings will be integers always (assuming they will come from some variable) you can change your code to parse them and the comparison will work correctly:
console.log(parseInt("10") > parseInt("9"));
Upvotes: 0