Jaketr00 February 2016

parseInt() check for NaN isn't working properly

I am working on a jQuery plugin and I need to make sure this value is a number, or a string with only a number. So to do this I made the following code, where val is a variable that may or may not be a number.

if (typeof val !== 'number') {//if "val" isn't a number
    if (typeof val === 'string' && parseInt(val) !== NaN) {//see if "val" is a string with only a number
        val = parseInt(val);
    }
}

But for some reason, while testing, even if val is a string with text, it still returns parseInt(val) !== NaN as true. I later tested with the Chrome console, and this is what I got:

incorrect return

As you can see, 'asf' is Not-a-Number. But wherever it returns true, it should return false, and wherever it returns false, it should return true. You can also see that I tested to make sure NaN isn't actually a string.

correct return

Above you can see the return values are the same, but this time it is correct.

Am I missing something? Or is there a different way I am supposed to do this?

Answers


Nechemya Kanelsky February 2016

NaN is not something you can compare to. you need to use :

isNaN(parseInt('asf')) // true

isNaN(parseInt('123')) // false


Evilzebra February 2016

The best solution to check if a value is a number or not is to use isNaN().

Post Status

Asked in February 2016
Viewed 1,735 times
Voted 6
Answered 2 times

Search




Leave an answer