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
Release: 2024-12-29 21:51:17
Original
788 people have browsed it

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));
}
Copy after login

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
Copy after login

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
Copy after login

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
Copy after login

Floats and Integers:

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

+'12.345'; // 12.345
parseInt(12.345); // 12
parseInt('12.345'); // 12
Copy after login

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
Copy after login

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