Home > Web Front-end > JS Tutorial > How Do I Reliably Check if a Number is NaN in JavaScript?

How Do I Reliably Check if a Number is NaN in JavaScript?

Barbara Streisand
Release: 2024-12-12 17:04:12
Original
410 people have browsed it

How Do I Reliably Check if a Number is NaN in JavaScript?

Determining if a Number is NaN in JavaScript

In JavaScript, when working with numeric values, it's important to verify if a number is NaN (Not-a-Number), which signifies an invalid numerical value. However, some methods commonly used for this purpose may not always yield the expected result.

Common Approaches that Fail

Attempts to compare numbers with NaN using equality operators, such as:

parseFloat('geoff') == NaN;
Copy after login

or

parseFloat('geoff') == Number.NaN;
Copy after login

will not return true in Firefox's JavaScript console. This is because NaN is a unique value that is neither equal to nor greater than or less than itself.

Reliable Method for Checking NaN

To accurately check if a number is NaN, use the isNaN() function:

isNaN(parseFloat("geoff"));
Copy after login

This function returns true if the specified value is NaN.

Note for Non-Numeric Values

For more comprehensive NaN checking that covers various data types, refer to:

How do you test for NaN in JavaScript?
Copy after login

The above is the detailed content of How Do I Reliably Check if a Number is NaN in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template