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!