Home > Web Front-end > JS Tutorial > Is There a JavaScript Equivalent to VB6's IsNumeric() Function?

Is There a JavaScript Equivalent to VB6's IsNumeric() Function?

Linda Hamilton
Release: 2024-12-12 11:42:10
Original
945 people have browsed it

Is There a JavaScript Equivalent to VB6's IsNumeric() Function?

Is There an Equivalent to VB6's IsNumeric() Function in JavaScript?

JavaScript offers analogous functions for checking if a string represents a valid number.

Using isNaN() to Validate Numeric Inputs:

For a comprehensive approach, use isNaN(), which returns true if the variable (whether it's a string or number) is not a valid number. This method effectively handles various scenarios:

isNaN(123);         // false
isNaN('123');       // false
isNaN('1e10000');   // false (Infinity, considered a number)
isNaN('foo');       // true
isNaN('10px');      // true
isNaN('');          // false
isNaN(' ');         // false
Copy after login

You can easily invert this check for an equivalent to IsNumeric():

function isNumeric(num) {
  return !isNaN(num);
}
Copy after login

Converting Strings to Numbers:

To transform a numeric string into a number:

+num;               // returns the numeric value or NaN
Copy after login

Examples:

+'12';              // 12
+'12.';             // 12
+'12..';            // NaN
+'.12';             // 0.12
+'..12';            // NaN
+'foo';             // NaN
+'12px';            // NaN
Copy after login

Loose Conversion with parseInt()

This function extracts the initial numeric value from a string, ignoring any trailing non-numeric characters:

parseInt(num);      // returns the numeric value or NaN
Copy after login

Examples:

parseInt('12');     // 12
parseInt('aaa');    // NaN
parseInt('12px');   // 12
parseInt('foo2');   // NaN
parseInt('12a5');   // 12
parseInt('0x10');   // 16
Copy after login

Handling Floats and Empty Strings

Note that parseInt() converts floats to integers, while num preserves decimal values. Empty strings are converted to zero by num but result in NaN when using parseInt().

The above is the detailed content of Is There a JavaScript Equivalent to VB6's IsNumeric() Function?. 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