7

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.

vivekraman
  • 165
  • 3
  • 7

3 Answers3

18

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.

Community
  • 1
  • 1
Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
1

NaN or (not a number) is a particular floating-point value, meaning a value that cannot be represented by computers (using the IEEE 754 floating point standard).

Crucially for you, the isNaN() function makes a best-effort to translate numbers to floating-point, which is why your example returns true. See, for example:

isNaN(100);                   //Returns false
isNaN("100");                 //Returns false
isNaN("ABC");                 //Returns true
isNaN("10C");                 //Returns true
isNaN(Math.sqrt(-1));         //Returns true

If you want to access a number such as "123." as a float, try using parseFloat():

parseFloat("123.");           //Returns 123

Furthermore, 123. is a valid number in javascript, which doesn't require a fractional part after the decimal point. So isNan() is behaving correctly, and should return false in this case.

fmark
  • 57,259
  • 27
  • 100
  • 107
0

The function is called "is Not a Number". So, this should return false in case you enter a number and true if it isn't. Even with the dot behind it this number is still valid. 123. just validates as 123 or 123.0.

Piro
  • 2,476
  • 3
  • 17
  • 19