Skip to content Skip to sidebar Skip to footer

Greater Than Returns Wrong Value On Numbers Lower Then 100. Javascript

This is my first javascript project, so I'm sure this code isn't pretty, and could be written in a much better way, but that aside, I've encountered a problem I just don't understa

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 "" as 0; it will also treat strings starting with 0x as hexadecimal

    var 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 "" as NaN, and treat any string prefixed with 0x as 0 (since it stops at the first invalid character)

    var num = parseInt(this.value, 10);
    
  • Number(...) does what + does

    var num = Number(this.value); // or variations above on +

Post a Comment for "Greater Than Returns Wrong Value On Numbers Lower Then 100. Javascript"