Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does isNaN(123.) return false?

Why does the Javascript function call isNaN(123.) return false? (notice the dot (.) after 123). Is this a universally acceptable number or will it cause errors downstream?

I'm validating whether a value is a valid decimal using isNaN along with split. Are there cross-browser issues with isNaN? Should I use a bespoke implementation?

Thanks.

like image 600
vivekraman Avatar asked Jun 10 '10 05:06

vivekraman


1 Answers

In JavaScript the grammar of a Numeric Literal is expressed like this:

DecimalIntegerLiteral . DecimalDigitsopt ExponentPartopt 

As you can see the DecimalDigits part after the dot is optional (opt suffix).

var n = 123.;
typeof n; // "number"

I wouldn't recommend the isNaN function to detect numbers, since type coercion can make some things look strange:

isNaN(""); // false, a empty string coerces to zero
isNaN("\n\t"); // false, a white-space string coerces to zero
isNaN(true); // false, boolean true coerces to 1
isNaN(false); // false, boolean false coerces to zero
isNaN(new Date); // false, Date objects coerce to its numeric timestamp
// etc...

isNaN should be used only to compare against NaN, since:

NaN == NaN; // false!
IsNaN(NaN); // true

If you want to detect Number objects, Number values or "parseable" numeric strings, give a look to this function I've posted some time ago.

like image 136
Christian C. Salvadó Avatar answered Oct 05 '22 23:10

Christian C. Salvadó