How do I check that a number is float or integer?
Solution 1:
check for a remainder when dividing by 1:
function isInt(n) {
return n % 1 === 0;
}
If you don't know that the argument is a number you need two tests:
function isInt(n){
return Number(n) === n && n % 1 === 0;
}
function isFloat(n){
return Number(n) === n && n % 1 !== 0;
}
Update 2019 5 years after this answer was written, a solution was standardized in ECMA Script 2015. That solution is covered in this answer.
Solution 2:
Try these functions to test whether a value is a number primitive value that has no fractional part and is within the size limits of what can be represented as an exact integer.
function isFloat(n) {
return n === +n && n !== (n|0);
}
function isInteger(n) {
return n === +n && n === (n|0);
}
Solution 3:
There is a method called Number.isInteger()
which is currently implemented in everything but IE. MDN also provides a polyfill for other browsers:
Number.isInteger = Number.isInteger || function(value) {
return typeof value === 'number' &&
isFinite(value) &&
Math.floor(value) === value;
};
However, for most uses cases, you are better off using Number.isSafeInteger
which also checks if the value is so high/low that any decimal places would have been lost anyway. MDN has a polyfil for this as well. (You also need the isInteger
pollyfill above.)
if (!Number.MAX_SAFE_INTEGER) {
Number.MAX_SAFE_INTEGER = 9007199254740991; // Math.pow(2, 53) - 1;
}
Number.isSafeInteger = Number.isSafeInteger || function (value) {
return Number.isInteger(value) && Math.abs(value) <= Number.MAX_SAFE_INTEGER;
};
Solution 4:
Why not something like this:
var isInt = function(n) { return parseInt(n) === n };
Solution 5:
You can use a simple regular expression:
function isInt(value) {
var er = /^-?[0-9]+$/;
return er.test(value);
}
Or you can use the below functions too, according your needs. They are developed by the PHPJS Project.
is_int()
=> Check if variable type is integer and if its content is integer
is_float()
=> Check if variable type is float and if its content is float
ctype_digit()
=> Check if variable type is string and if its content has only decimal digits
Update 1
Now it checks negative numbers too, thanks for @ChrisBartley comment!