Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What causes isNaN to malfunction? [duplicate]

I'm simply trying to evaluate if an input is a number, and figured isNaN would be the best way to go. However, this causes unreliable results. For instance, using the following method:

function isNumerical(value) {
    var isNum = !isNaN(value);
    return isNum ? "<mark>numerical</mark>" : "not numerical";
}

on these values:

isNumerical(123));     // => numerical
isNumerical("123"));   // => numerical
isNumerical(null));    // => numerical
isNumerical(false));   // => numerical
isNumerical(true));    // => numerical
isNumerical());        // => not numerical

shown in this fiddle: http://jsfiddle.net/4nm7r/1

Why doesn't isNaN always work for me?

like image 801
Ky. Avatar asked Jun 13 '13 19:06

Ky.


Video Answer


3 Answers

isNaN returns true if the value passed is not a number(NaN)(or if it cannot be converted to a number, so, null, true and false will be converted to 0), otherwise it returns false. In your case, you have to remove the ! before the function call!

It is very easy to understand the behaviour of your script. isNaN simply checks if a value can be converted to an int. To do this, you have just to multiply or divide it by 1, or subtract or add 0. In your case, if you do, inside your function, alert(value * 1); you will see that all those passed values will be replaced by a number(0, 1, 123) except for undefined, whose numerical value is NaN.

You can't compare any value to NaN because it will never return false(even NaN === NaN), I think that's because NaN is dynamically generated... But I'm not sure.

Anyway you can fix your code by simply doing this:

function isNumerical(value) {
    var isNum = !isNaN(value / 1); //this will force the conversion to NaN or a number
    return isNum ? "<mark>numerical</mark>" : "not numerical";
}
like image 155
Niccolò Campolungo Avatar answered Oct 17 '22 10:10

Niccolò Campolungo


Your ternary statement is backward, if !isNaN() returns true you want to say "numerical"

return isNum ? "not numerical" : "<mark>numerical</mark>";

should be:

return isNum ? "<mark>numerical</mark>" : "not numerical";

See updated fiddle:

http://jsfiddle.net/4nm7r/1/

like image 35
Hunter McMillen Avatar answered Oct 17 '22 11:10

Hunter McMillen


Now that you already fixed the reversed logic pointed out on other answers, use parseFloat to get rid of the false positives for true, false and null:

var isNum = !isNaN(parseFloat(value));

Just keep in mind the following kinds of outputs from parseFloat:

parseFloat("200$"); // 200
parseFloat("200,100"); // 200
parseFloat("200 foo"); // 200
parseFloat("$200"); // NaN

(i.e, if the string starts with a number, parseFloat will extract the first numeric part it can find)

like image 1
bfavaretto Avatar answered Oct 17 '22 11:10

bfavaretto