Greater Than Returns Wrong Value On Numbers Lower Then 100. Javascript
Solution 1:
value
on input
elements is always a string. While that won't be a problem initially, when you're comparing this.value
to the 100
you've put in the array to start with, you then push this.value
into the array as-is (as a string). That means later, you'll end up comparing that stored string with another this.value
value, which is also a string. If either operand to >
is a number, it will coerce the other operand to number (the way +
does, see below), but if both operands are strings, it will do a lexical comparison, not a numeric one, and "100"
is indeed <
"99"
because "1"
is <
"9"
.
So you want to convert this.value
to a number early on, and then use that number both when comparing and when pushing into your array. You have many ways to do that:
The unary
+
will require the entire string to be a valid number, but will treat""
as0
; it will also treat strings starting with0x
as hexadecimalvar num = +this.value; // or perhapsvar num = this.value === "" ? NaN : +this.value; // or evenvar str = this.value.trim(); // .trim can be shimmed on obsolete browsersvar num = str === "" ? NaN : +str;
parseInt(..., 10)
(the 10 is specifying the radix [number base] to use) will allow garbage at the end of the string, treat""
asNaN
, and treat any string prefixed with0x
as0
(since it stops at the first invalid character)var num = parseInt(this.value, 10);
Number(...)
does what+
doesvar num = Number(this.value); // or variations above on +
Post a Comment for "Greater Than Returns Wrong Value On Numbers Lower Then 100. Javascript"