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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With