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?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-29 21:51:17793browse

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

Checking String for Numeric Value

Question:

Exists there a function similar to VB6's IsNumeric() function that checks if a given string represents a valid numeric value?

Answer:

Robust Implementation for Whitespace and Radix Handling:

function isNumeric(str) {
  if (typeof str != "string") return false; // Only process strings
  return !isNaN(str) && !isNaN(parseFloat(str));
}

Verification Using isNaN():

To determine if a string (or variable) contains a valid number, utilize the isNaN() function:

isNaN(num); // Returns true if the value is not a number

Converting String to Number:

For strings containing exclusively numeric characters, the operator converts them to numbers:

+num; // Numeric value or NaN if string is not purely numeric

Loose String-to-Number Conversion:

To extract numeric values from strings containing non-numeric characters, use parseInt():

parseInt(num); // Numeric value or NaN if string starts with non-numeric characters

Floats and Integers:

Note that parseInt() truncates floats to integers, unlike num:

+'12.345'; // 12.345
parseInt(12.345); // 12
parseInt('12.345'); // 12

Empty Strings:

num and isNaN() treat empty strings as zero, while parseInt() considers them as NaN:

+''; // 0
+'   '; // 0
isNaN(''); // false
isNaN('   '); // false
parseInt(''); // NaN
parseInt('   '); // NaN

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!

Statement:
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