# How do I check that a number is float or integer?

## How do I check that a number is float or integer?

How to find that a number is float or integer?
1.25 –> float
1 –> integer
0 –> integer
0.25 –> float

### 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;
}
``````

### 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:

Why not something like this:

``````var isInt = function(n) { return parseInt(n) === n };
``````

### Solution 4:

There is a method called `Number.isInteger()` which is currently implemented only in latest Firefox and is still a part of EcmaScript 6 proposal. However MDN provides a polyfill for the other browsers, which matches the one specified in ECMA harmony:

``````if (!Number.isInteger) {
Number.isInteger = function isInteger (nVal) {
return typeof nVal === "number" && isFinite(nVal) && nVal > -9007199254740992 && nVal < 9007199254740992 && Math.floor(nVal) === nVal;
};
}
``````

### 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!

### Solution 6:

Here are efficient functions that check if the value is a number or can be safely converted to a number:

``````function isNumber(value) {
if ((undefined === value) || (null === value)) {
return false;
}
if (typeof value == 'number') {
return true;
}
return !isNaN(value - 0);
}
``````

And for integers (would return false if the value is a float):

``````function isInteger(value) {
if ((undefined === value) || (null === value)) {
return false;
}
return value % 1 == 0;
}
``````

The efficiency here is that parseInt (or parseNumber) are avoided when the value already is a number. Both parsing functions always convert to string first and then attempt to parse that string, which would be a waste if the value already is a number.

Thank you to the other posts here for providing further ideas for optimization!