How do you check that a number is NaN in JavaScript?

前端 未结 30 2669
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 06:19

I’ve only been trying it in Firefox’s JavaScript console, but neither of the following statements return true:

parseFloat(\'geoff\') == NaN;

parseFloat(\'ge         


        
相关标签:
30条回答
  • 2020-11-22 06:55

    While @chiborg 's answer IS correct, there is more to it that should be noted:

    parseFloat('1.2geoff'); // => 1.2
    isNaN(parseFloat('1.2geoff')); // => false
    isNaN(parseFloat('.2geoff')); // => false
    isNaN(parseFloat('geoff')); // => true
    

    Point being, if you're using this method for validation of input, the result will be rather liberal.

    So, yes you can use parseFloat(string) (or in the case of full numbers parseInt(string, radix)' and then subsequently wrap that with isNaN(), but be aware of the gotcha with numbers intertwined with additional non-numeric characters.

    0 讨论(0)
  • 2020-11-22 06:55

    I wrote this answer to another question on StackOverflow where another checks when NaN == null but then it was marked as duplicate so I don't want to waste my job.

    Look at Mozilla Developer Network about NaN.


    Short answer

    Just use distance || 0 when you want to be sure you value is a proper number or isNaN() to check it.

    Long answer

    The NaN (Not-a-Number) is a weirdo Global Object in javascript frequently returned when some mathematical operation failed.

    You wanted to check if NaN == null which results false. Hovewer even NaN == NaN results with false.

    A Simple way to find out if variable is NaN is an global function isNaN().

    Another is x !== x which is only true when x is NaN. (thanks for remind to @raphael-schweikert)

    But why the short answer worked?

    Let's find out.

    When you call NaN == false the result is false, same with NaN == true.

    Somewhere in specifications JavaScript has an record with always false values, which includes:

    • NaN - Not-a-Number
    • "" - empty string
    • false - a boolean false
    • null - null object
    • undefined - undefined variables
    • 0 - numerical 0, including +0 and -0
    0 讨论(0)
  • 2020-11-22 06:55

    I've created this little function that works like a charm. Instead of checking for NaN which seems to be counter intuitive, you check for a number. I'm pretty sure I am not the first to do it this way, but I thought i'd share.

    function isNum(val){
        var absVal = Math.abs(val);
        var retval = false;
        if((absVal-absVal) == 0){
            retval = true
        }
    
        return retval;
    }
    
    0 讨论(0)
  • 2020-11-22 06:57

    Another solution is mentioned in MDN's parseFloat page

    It provides a filter function to do strict parsing

    var filterFloat = function (value) {
        if(/^(\-|\+)?([0-9]+(\.[0-9]+)?|Infinity)$/
          .test(value))
          return Number(value);
      return NaN;
    }
    
    
    console.log(filterFloat('421'));               // 421
    console.log(filterFloat('-421'));              // -421
    console.log(filterFloat('+421'));              // 421
    console.log(filterFloat('Infinity'));          // Infinity
    console.log(filterFloat('1.61803398875'));     // 1.61803398875
    console.log(filterFloat('421e+0'));            // NaN
    console.log(filterFloat('421hop'));            // NaN
    console.log(filterFloat('hop1.61803398875'));  // NaN
    

    And then you can use isNaN to check if it is NaN

    0 讨论(0)
  • 2020-11-22 06:58

    I just want to share another alternative, it's not necessarily better than others here, but I think it's worth looking at:

    function customIsNaN(x) { return (typeof x == 'number' && x != 0 && !x); }
    

    The logic behind this is that every number except 0 and NaN are cast to true.

    I've done a quick test, and it performs as good as Number.isNaN and as checking against itself for false. All three perform better than isNan

    The results

    customIsNaN(NaN);            // true
    customIsNaN(0/0);            // true
    customIsNaN(+new Date('?')); // true
    
    customIsNaN(0);          // false
    customIsNaN(false);      // false
    customIsNaN(null);       // false
    customIsNaN(undefined);  // false
    customIsNaN({});         // false
    customIsNaN('');         // false
    

    May become useful if you want to avoid the broken isNaN function.

    0 讨论(0)
  • 2020-11-22 07:00

    Maybe also this:

    function isNaNCustom(value){
        return value.toString() === 'NaN' && 
               typeof value !== 'string' && 
               typeof value === 'number'
    }
    
    0 讨论(0)
提交回复
热议问题