I\'m doing some trouble-shooting and want to add a check that a parameter to a function is a number. How do I do this?
Something like this...
function fn
function fn(id){
if((parseFloat(id) == parseInt(id)) && !isNaN(id)){
return true;
} else {
return false;
}
}
Check if the type is number, and whether it is an int using parseInt
:
if (typeof id == "number" && id == parseInt(id))
=== means strictly equals to and == checks if values are equal. that means "2"==2 is true but "2"===2 is false.
using regular expression
var intRegex = /^\d+$/;
if(intRegex.test(num1)) {
//num1 is a valid integer
}
example of == vs. ===
function fn(id) {
return typeof(id) === 'number';
}
To also check if it’s an integer:
function fn(id) {
return typeof(id) === 'number' &&
isFinite(id) &&
Math.round(id) === id;
}
i'd say
n === parseInt(n)
is enough. note three '===' - it checks both type and value
function fn(id) {
var x = /^(\+|-)?\d+$/;
if (x.test(id)) {
//integer
return true;
}
else {
//not an integer
return false;
}
}
Test fiddle: http://jsfiddle.net/xLYW7/