0

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?

ZomoXYZ
  • 1,763
  • 21
  • 44

2 Answers2

18

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

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

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

1

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

EvilZebra
  • 1,072
  • 8
  • 18