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
You can easily invert this check for an equivalent to IsNumeric():
function isNumeric(num) { return !isNaN(num); }
Converting Strings to Numbers:
To transform a numeric string into a number:
+num; // returns the numeric value or NaN
Examples:
+'12'; // 12 +'12.'; // 12 +'12..'; // NaN +'.12'; // 0.12 +'..12'; // NaN +'foo'; // NaN +'12px'; // NaN
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
Examples:
parseInt('12'); // 12 parseInt('aaa'); // NaN parseInt('12px'); // 12 parseInt('foo2'); // NaN parseInt('12a5'); // 12 parseInt('0x10'); // 16
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!