Javascript is a dynamically typed langauges. This feature causes for Arrays, Booleans, and other types to be converted to a numeric values depending on usage.
However this feature can cause headarches when trying to detect numbers.
For example, isNaN() detects if a value is a non-number. That’s what NaN stands for, “Not a number”.
So you might think that the opposite result from isNaN() would indicate if a value is a number.
// Works for most cases but not for strict comparisons.
var isNumber = function(val){
return !isNaN( val );
}; |
// Works for most cases but not for strict comparisons.
var isNumber = function(val){
return !isNaN( val );
};
Example:
Note: Click the “result” tab to run the test cases in jsfiddle.net.
Solution:
So here’s a simple fix for isNaN and isNumber.
// isNaN2 returns a boolean for if a value is not a number or +-Infinity
var isNaN2 = (function (global) {
var _isNaN = global.isNaN;
return function (val) {
return _isNaN("" + val) || (typeof val === "object" && !(val || "").hasOwnProperty('push'));
};
}(this));
// isNumeric returns a boolean for if a value is a number or +-Infinity
var isNumeric = (function (global) {
var _isNaN = global.isNaN;
return function (val) {
return !_isNaN("" + val)&&(typeof val !== "object" || (val || "").hasOwnProperty('push'));
};
}(this)); |
// isNaN2 returns a boolean for if a value is not a number or +-Infinity
var isNaN2 = (function (global) {
var _isNaN = global.isNaN;
return function (val) {
return _isNaN("" + val) || (typeof val === "object" && !(val || "").hasOwnProperty('push'));
};
}(this));
// isNumeric returns a boolean for if a value is a number or +-Infinity
var isNumeric = (function (global) {
var _isNaN = global.isNaN;
return function (val) {
return !_isNaN("" + val)&&(typeof val !== "object" || (val || "").hasOwnProperty('push'));
};
}(this));
isNaN vs isNaN2
Testcases for isNaN2 and isNumeric
*Update*
Well it turns out that jQuery has a better implementation. The only difference is that infinity is not a number, which is correct.
$.isNumeric = function( obj ){
return !isNaN( parseFloat( obj ) ) && isFinite( obj );
}; |
$.isNumeric = function( obj ){
return !isNaN( parseFloat( obj ) ) && isFinite( obj );
};
api.jquery.com/jQuery.isNumeric