开发者

Why does isNaN(123.) return false?

开发者 https://www.devze.com 2023-01-03 03:34 出处:网络
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?

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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消