[javascript] 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

This question is related to javascript types numbers

The answer is


There is Number.isInteger(number) to check this. Doesn't work in Internet Explorer but that browser isn't used anymore. If you need string like "90" to be an integer (which wasnt the question) try Number.isInteger(Number(number)). The "official" isInteger considers 9.0 as an integer, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number. It looks like most answers are correct for older browsers but modern browsers have moved on and actually support float integer check.


function int(a) {
  return a - a === 0 && a.toString(32).indexOf('.') === -1
}

function float(a) {
  return a - a === 0 && a.toString(32).indexOf('.') !== -1
}

You can add typeof a === 'number' if you want to exclude strings.


The functions below guard against empty strings,undefines,nulls, and max/min value ranges. The Javascript engine should have built in these functions from day one. :)

Enjoy!

function IsInteger(iVal) {
    var iParsedVal; //our internal converted int value


    iParsedVal = parseInt(iVal,10);

    if (isNaN(iParsedVal) || Infinity == iParsedVal || -Infinity == iParsedVal) //sanity check - guard against empty strings and max/min values
        return false;
    else
        return Number(iVal) === (iParsedVal | 0); //the 2nd operand group (intValue | 0), evaluates to true only if the intValue is an integer; so an int type will only return true
}

function IsFloat(fVal) {
    var fParsedVal; //our internal converted float value


    fParsedVal = parseFloat(fVal);

    if (isNaN(fParsedVal) || Infinity == fParsedVal || -Infinity == fParsedVal) //sanity check - guard against empty strings and max/min values
        return false;
    else
        return !!(fVal % 1); //true only if there is a fractional value after the mod op; the !! returns the opposite value of the op which reflects the function's return value
}

In java script all the numbers are internally 64 bit floating point, same as double in java. There are no diffrent types in javascript, all are represented by type number. Hence you wil l not be able make a instanceof check. However u can use the above solutions given to find out if it is a fractional number. designers of java script felt with a single type they can avoid numerous type cast errors.


var isInt = function (n) { return n === (n | 0); };

Haven't had a case where this didn't do the job.


This maybe isn't as performant as the % answer, which prevents you from having to convert to a string first, but I haven't seen anyone post it yet, so here's another option that should work fine:

function isInteger(num) {
    return num.toString().indexOf('.') === -1;
}

function isInteger(n) {
   return ((typeof n==='number')&&(n%1===0));
}

function isFloat(n) {
   return ((typeof n==='number')&&(n%1!==0));
}

function isNumber(n) {
   return (typeof n==='number');
}

I find this the most elegant way:

function isInteger(n) {
    return n === (n^0);
}

It cares also to return false in case of a non-numeric value.


YourJS provides the following two functions which work for all numbers including returning false for -Infinity and Infinity:

function isFloat(x) {
  return typeOf(x, 'Number') && !!(x % 1);
}

function isInt(x) {
  return typeOf(x, 'Number') && x % 1 == 0;
}

Due to the fact that typeOf() is a YourJS internal function, if you wanted to use these definitions you can download the version for just these functions here: http://yourjs.com/snippets/build/34


It really depends on what you want to achieve. If you want to "emulate" strongly typed languages then I suggest you not trying. As others mentioned all numbers have the same representation (the same type).

Using something like Claudiu provided:

isInteger( 1.0 ) -> true

which looks fine for common sense, but in something like C you would get false


to check the number is Int or not and apply 2 decimal format, you can use the formula below in React-Native.

isInt = (n) => {
        return n % 1 === 0;
     }

    show = (x) => {
        if(x) {
           if (this.isInt(x)) {
               return ${x} 
           }
           else {
            return ${x.toFixed(2)}
           }
        }
    }

This is mine:

function isInt(quale) {
    var valore = $('#'+quale).val().toLowerCase();
    if (isNaN(Number(String(valore))) || (valore.indexOf("e") > 0)) {
        // Not int
    } else {
        // Is Int!
    }
}

And this:

function isFloat(quale) {
   var valore = $('#'+quale).val();
   valore = valore.replace(",", "");
   if (isNaN(String(valore)) || (valore.indexOf("e") > 0)) {
    // Not Float
   } else {
    // Float
   }
}

Ad majora!


Another method is:

    function isFloat(float) {
        return /\./.test(float.toString());
    }

Might not be as efficient as the others but another method all the same.


Why not something like this:

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

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

Here's what I use for integers:

Math.ceil(parseFloat(val)) === val

Short, nice :) Works all the time. This is what David Flanagan suggests if I'm not mistaken.


Condtion for floating validation :

if (lnk.value == +lnk.value && lnk.value != (lnk.value | 0)) 

Condtion for Integer validation :

if (lnk.value == +lnk.value && lnk.value == (lnk.value | 0)) 

Hope this might be helpful.


This solution worked for me.

<html>
<body>
  <form method="post" action="#">
    <input type="text" id="number_id"/>
    <input type="submit" value="send"/>
  </form>
  <p id="message"></p>
  <script>
    var flt=document.getElementById("number_id").value;
    if(isNaN(flt)==false && Number.isInteger(flt)==false)
    {
     document.getElementById("message").innerHTML="the number_id is a float ";
    }
   else 
   {
     document.getElementById("message").innerHTML="the number_id is a Integer";
   }
  </script>
</body>
</html>

You can use the Number.isInteger() method to check if the number is an integer or a float by dividing them for example:

    function isNumberFloatOrInteger(a, b){
     if(Number.isInteger(a / b)){
      return true;
      }
      else{ return false };
}

Note: isInteger() is not compatible with internet explorer.


Some times Number objects don't allow you to use direct the mod operator (%), if you are facing that case you can use this solution.

if(object instanceof Number ){
   if( ((Number) object).doubleValue() % 1 == 0 ){
      //your object is an integer
   }
   else{
      //your object is a double
   }
}

With this you can check if a string or a number is "decimal" (float properly):

var IsDecimal = function(num){
    return ((num.toString().split('.').length) <= 2 && num.toString().match(/^[\+\-]?\d*\.?\d+(?:[Ee][\+\-]?\d+)?$/)) ? (!isNaN(Number.parseFloat(num))) : false ;
}

and this other works for check if a string or a number is Integer:

var IsInteger = function(num){
    return ((num.toString().split('.').length) == 1 && num.toString().match(/^[\-]?\d+$/)) ? (!isNaN(Number.parseInt(num))) : false ;
}

_x000D_
_x000D_
var IsDecimal = function(num){
    return ((num.toString().split('.').length) <= 2 && num.toString().match(/^[\+\-]?\d*\.?\d+(?:[Ee][\+\-]?\d+)?$/)) ? (!isNaN(Number.parseFloat(num))) : false ;
}

var IsInteger = function(num){
    return ((num.toString().split('.').length) == 1 && num.toString().match(/^[\-]?\d+$/)) ? (!isNaN(Number.parseInt(num))) : false ;
}


console.log("-------------- As string --------------");
console.log("Integers:");
console.log("0 = " + IsInteger("0"));
console.log("34 = " + IsInteger("34"));
console.log(".34 = " + IsInteger(".34"));
console.log("3.4 = " + IsInteger("3.4"));
console.log("3e = " + IsInteger("3e"));
console.log("e3 = " + IsInteger("e3"));
console.log("-34 = " + IsInteger("-34"));
console.log("--34 = " + IsInteger("--34"));
console.log("034 = " + IsInteger("034"));
console.log("0-34 = " + IsInteger("0-34"));
console.log("Floats/decimals:");
console.log("0 = " + IsDecimal("0"));
console.log("64 = " + IsDecimal("64"));
console.log(".64 = " + IsDecimal(".64"));
console.log("6.4 = " + IsDecimal("6.4"));
console.log("6e2 = " + IsDecimal("6e2"));
console.log("6e = " + IsDecimal("6e"));
console.log("e6 = " + IsDecimal("e6"));
console.log("-64 = " + IsDecimal("-64"));
console.log("--64 = " + IsDecimal("--64"));
console.log("064 = " + IsDecimal("064"));
console.log("0-64 = " + IsDecimal("0-64"));
console.log("\n-------------- As numbers --------------");
console.log("Integers:");
console.log("0 = " + IsInteger(0));
console.log("34 = " + IsInteger(34));
console.log(".34 = " + IsInteger(0.34));
console.log("3.4 = " + IsInteger(3.4));
console.log("-34 = " + IsInteger(-34));
console.log("034 = " + IsInteger(034));
console.log("0-34 = " + IsInteger(0-34));
console.log("Floats/decimals:");
console.log("0 = " + IsDecimal(0));
console.log("64 = " + IsDecimal(64));
console.log(".64 = " + IsDecimal(0.64));
console.log("6.4 = " + IsDecimal(6.4));
console.log("6e2 = " + IsDecimal(6e2));
console.log("-64 = " + IsDecimal(-64));
console.log("064 = " + IsDecimal(064));
console.log("0-64 = " + IsDecimal(0-64));
_x000D_
_x000D_
_x000D_


How about this one?

isFloat(num) {
    return typeof num === "number" && !Number.isInteger(num);
}

Here's my code. It checks to make sure it's not an empty string (which will otherwise pass) and then converts it to numeric format. Now, depending on whether you want '1.1' to be equal to 1.1, this may or may not be what you're looking for.

var isFloat = function(n) {
    n = n.length > 0 ? Number(n) : false;
    return (n === parseFloat(n));
};
var isInteger = function(n) {
    n = n.length > 0 ? Number(n) : false;
    return (n === parseInt(n));
};

var isNumeric = function(n){

   if(isInteger(n) || isFloat(n)){
        return true;
   }
   return false;

};

!!(24%1) // false
!!(24.2%1) // true

Trying some of the answers here I ended up writing this solution. This works also with numbers inside a string.

function isInt(number) {
    if(!/^["|']{0,1}[-]{0,1}\d{0,}(\.{0,1}\d+)["|']{0,1}$/.test(number)) return false;
    return !(number - parseInt(number));
}

function isFloat(number) {
    if(!/^["|']{0,1}[-]{0,1}\d{0,}(\.{0,1}\d+)["|']{0,1}$/.test(number)) return false;
    return number - parseInt(number) ? true : false;
}

_x000D_
_x000D_
    var tests = {_x000D_
        'integer' : 1,_x000D_
        'float' : 1.1,_x000D_
        'integerInString' : '5',_x000D_
        'floatInString' : '5.5',_x000D_
        'negativeInt' : -345,_x000D_
        'negativeFloat' : -34.98,_x000D_
        'negativeIntString' : '-45',_x000D_
        'negativeFloatString' : '-23.09',_x000D_
        'notValidFalse' : false,_x000D_
        'notValidTrue' : true,_x000D_
        'notValidString' : '45lorem',_x000D_
        'notValidStringFloat' : '4.5lorem',_x000D_
        'notValidNan' : NaN,_x000D_
        'notValidObj' : {},_x000D_
        'notValidArr' : [1,2],_x000D_
    };_x000D_
_x000D_
    function isInt(number) {_x000D_
        if(!/^["|']{0,1}[-]{0,1}\d{0,}(\.{0,1}\d+)["|']{0,1}$/.test(number)) return false;_x000D_
        return !(number - parseInt(number));_x000D_
    }_x000D_
    _x000D_
    function isFloat(number) {_x000D_
        if(!/^["|']{0,1}[-]{0,1}\d{0,}(\.{0,1}\d+)["|']{0,1}$/.test(number)) return false;_x000D_
        return number - parseInt(number) ? true : false;_x000D_
    }_x000D_
_x000D_
    function testFunctions(obj) {_x000D_
        var keys = Object.keys(obj);_x000D_
        var values = Object.values(obj);_x000D_
_x000D_
        values.forEach(function(element, index){_x000D_
            console.log(`Is ${keys[index]} (${element}) var an integer? ${isInt(element)}`);_x000D_
            console.log(`Is ${keys[index]} (${element}) var a float? ${isFloat(element)}`);_x000D_
        });_x000D_
    }_x000D_
_x000D_
    testFunctions(tests);
_x000D_
_x000D_
_x000D_


For Float

var decimal=  /^[-+]?[0-9]+\.[0-9]+$/; 

if (!price.match(decimal)) {
      alert('Please enter valid float');
      return false;
    }

For integer

var number = /^\d+$/; 

if (!price.match(number)) {
      alert('Please enter valid integer');
      return false;
    }

For those curious, using Benchmark.js I tested the most up-voted answers (and the one posted today) on this post, here are my results:

var n = -10.4375892034758293405790;
var suite = new Benchmark.Suite;
suite
    // kennebec
    .add('0', function() {
        return n % 1 == 0;
    })
    // kennebec
    .add('1', function() {
        return typeof n === 'number' && n % 1 == 0;
    })
    // kennebec
    .add('2', function() {
        return typeof n === 'number' && parseFloat(n) == parseInt(n, 10) && !isNaN(n);
    })

    // Axle
    .add('3', function() {
        return n.toString().indexOf('.') === -1;
    })

    // Dagg Nabbit
    .add('4', function() {
        return n === +n && n === (n|0);
    })

    // warfares
    .add('5', function() {
        return parseInt(n) === n;
    })

    // Marcio Simao
    .add('6', function() {
        return /^-?[0-9]+$/.test(n.toString());
    })

    // Tal Liron
    .add('7', function() {
        if ((undefined === n) || (null === n)) {
            return false;
        }
        if (typeof n == 'number') {
            return true;
        }
        return !isNaN(n - 0);
    });

// Define logs and Run
suite.on('cycle', function(event) {
    console.log(String(event.target));
}).on('complete', function() {
    console.log('Fastest is ' + this.filter('fastest').pluck('name'));
}).run({ 'async': true });

0 x 12,832,357 ops/sec ±0.65% (90 runs sampled)
1 x 12,916,439 ops/sec ±0.62% (95 runs sampled)
2 x 2,776,583 ops/sec ±0.93% (92 runs sampled)
3 x 10,345,379 ops/sec ±0.49% (97 runs sampled)
4 x 53,766,106 ops/sec ±0.66% (93 runs sampled)
5 x 26,514,109 ops/sec ±2.72% (93 runs sampled)
6 x 10,146,270 ops/sec ±2.54% (90 runs sampled)
7 x 60,353,419 ops/sec ±0.35% (97 runs sampled)

Fastest is 7 Tal Liron

function isInt(n) 
{
    return n != "" && !isNaN(n) && Math.round(n) == n;
}
function isFloat(n){
    return n != "" && !isNaN(n) && Math.round(n) != n;
}

works for all cases.


It really doesn't have to be so complicated. The numeric value of an integer's parseFloat() and parseInt() equivalents will be the same. Thus you can do like so:

function isInt(value){ 
    return (parseFloat(value) == parseInt(value)) && !isNaN(value);
}

Then

if (isInt(x)) // do work

This will also allow for string checks and thus is not strict. If want a strong type solution (aka, wont work with strings):

function is_int(value){ return !isNaN(parseInt(value * 1) }

I needed to check an input value if it's integer or float and to do that I've come up with the following:

_x000D_
_x000D_
function isInteger(x) {_x000D_
  var integer = parseInt(x, 10);_x000D_
  if (!isNaN(integer) && !isFloat(x)) {_x000D_
    return true;_x000D_
  }_x000D_
  return false;_x000D_
}_x000D_
_x000D_
function isFloat(x) {_x000D_
  var f = parseFloat(x);_x000D_
  var floor = Math.floor(f);_x000D_
  var fraction = f - floor;_x000D_
  if (fraction > 0) {_x000D_
    return true;_x000D_
  }_x000D_
  return false;_x000D_
}_x000D_
_x000D_
var cases = [_x000D_
  "1",_x000D_
  "1.00",_x000D_
  "1.01",_x000D_
  "0.05",_x000D_
  "ab1",_x000D_
  "ab1.1",_x000D_
  1,_x000D_
  1.00,_x000D_
  1.01,_x000D_
  0.05,_x000D_
  1e+5,_x000D_
  "",_x000D_
  true,_x000D_
  false,_x000D_
  null,_x000D_
  NaN,_x000D_
  undefined,_x000D_
];_x000D_
_x000D_
console.log("isInteger()");_x000D_
for (var i = 0; i < cases.length; i++) {_x000D_
  console.log(cases[i], isInteger(cases[i]));_x000D_
}_x000D_
_x000D_
console.log("\nisFloat()");_x000D_
for (var i = 0; i < cases.length; i++) {_x000D_
  console.log(cases[i], isFloat(cases[i]));_x000D_
}
_x000D_
_x000D_
_x000D_


Based on all that I have seen here, I've created my own set of functions to test for what I need:

function NumberValidator() {
this.isFloat = function (n) {
    return typeof(n)==="number" && n === +n && Math.round(n) !== n;
};

this.isInteger = function (n) {
    return typeof(n)==="number" && n === +n && Math.round(n) === n;
};

this.isFloatOrInteger = function (n) {
    return this.isFloat(n) || this.isInteger(n);
};

this.isNonZeroFloatOrInteger = function (n) {
    return this.isFloatOrInteger(n) && n > 0;
};

this.isNonZeroInteger = function (n) {
    return this.isInteger(n) && n > 0;
};
}

However, shime's solution is shorter and with less checks, so it might be a better one.


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!


For integers I use this

function integer_or_null(value) {
    if ((undefined === value) || (null === value)) {
        return null;
    }
    if(value % 1 != 0) {
        return null;
    }
    return value;
}

I like this little function, which will return true for both positive and negative integers:

function isInt(val) {
    return ["string","number"].indexOf(typeof(val)) > -1 && val !== '' && !isNaN(val+".0");
}

This works because 1 or "1" becomes "1.0", which isNaN() returns false on (which we then negate and return), but 1.0 or "1.0" becomes "1.0.0", while "string" becomes "string.0", neither of which are numbers, so isNaN() returns false (and, again, gets negated).

If you only want positive integers, there's this variant:

function isPositiveInt(val) {
    return ["string","number"].indexOf(typeof(val)) > -1 && val !== '' && !isNaN("0"+val);
}

or, for negative integers:

function isNegativeInt(val) {
    return `["string","number"].indexOf(typeof(val)) > -1` && val !== '' && isNaN("0"+val);
}

isPositiveInt() works by moving the concatenated numeric string ahead of the value to be tested. For example, isPositiveInt(1) results in isNaN() evaluating "01", which evaluates false. Meanwhile, isPositiveInt(-1) results in isNaN() evaluating "0-1", which evaluates true. We negate the return value and that gives us what we want. isNegativeInt() works similarly, but without negating the return value of isNaN().

Edit:

My original implementation would also return true on arrays and empty strings. This implementation doe not have that defect. It also has the benefit of returning early if val is not a string or number, or if it's an empty string, making it faster in these cases. You can further modify it by replacing the first two clauses with

typeof(val) != "number"

if you only want to match literal numbers (and not strings)

Edit:

I can't post comments yet, so I'm adding this to my answer. The benchmark posted by @Asok is very informative; however, the fastest function does not fit the requirements, as it also returns TRUE for floats, arrays, booleans, and empty strings.

I created the following test suite to test each of the functions, adding my answer to the list, as well (function 8, which parses strings, and function 9, which does not):

funcs = [
    function(n) {
        return n % 1 == 0;
    },
    function(n) {
        return typeof n === 'number' && n % 1 == 0;
    },
    function(n) {
        return typeof n === 'number' && parseFloat(n) == parseInt(n, 10) && !isNaN(n);
    },
    function(n) {
        return n.toString().indexOf('.') === -1;
    },
    function(n) {
        return n === +n && n === (n|0);
    },
    function(n) {
        return parseInt(n) === n;
    },
    function(n) {
        return /^-?[0-9]+$/.test(n.toString());
    },
    function(n) {
        if ((undefined === n) || (null === n)) {
            return false;
        }
        if (typeof n == 'number') {
            return true;
        }
        return !isNaN(n - 0);
    },
    function(n) {
        return ["string","number"].indexOf(typeof(n)) > -1 && n !== '' && !isNaN(n+".0");
    }
];
vals = [
    [1,true],
    [-1,true],
    [1.1,false],
    [-1.1,false],
    [[],false],
    [{},false],
    [true,false],
    [false,false],
    [null,false],
    ["",false],
    ["a",false],
    ["1",null],
    ["-1",null],
    ["1.1",null],
    ["-1.1",null]
];

for (var i in funcs) {
    var pass = true;
    console.log("Testing function "+i);
    for (var ii in vals) {
        var n = vals[ii][0];
        var ns;
        if (n === null) {
            ns = n+"";
        } else {
            switch (typeof(n)) {
                case "string":
                    ns = "'" + n + "'";
                    break;
                case "object":
                    ns = Object.prototype.toString.call(n);
                    break;
                default:
                    ns = n;
            }
            ns = "("+typeof(n)+") "+ns;
        }

        var x = vals[ii][1];
        var xs;
        if (x === null) {
            xs = "(ANY)";
        } else {
            switch (typeof(x)) {
                case "string":
                    xs = "'" + n + "'";
                    break;
                case "object":
                    xs = Object.prototype.toString.call(x);
                    break;
                default:
                    xs = x;
            }
            xs = "("+typeof(x)+") "+xs;
        }

        var rms;
        try {
            var r = funcs[i](n);
            var rs;
            if (r === null) {
                rs = r+"";
            } else {
                switch (typeof(r)) {
                    case "string":
                        rs = "'" + r + "'";
                        break;
                    case "object":
                        rs = Object.prototype.toString.call(r);
                        break;
                    default:
                        rs = r;
                }
                rs = "("+typeof(r)+") "+rs;
            }

            var m;
            var ms;
            if (x === null) {
                m = true;
                ms = "N/A";
            } else if (typeof(x) == 'object') {
                m = (xs === rs);
                ms = m;
            } else {
                m = (x === r);
                ms = m;
            }
            if (!m) {
                pass = false;
            }
            rms = "Result: "+rs+", Match: "+ms;
        } catch (e) {
            rms = "Test skipped; function threw exception!"
        }

        console.log("    Value: "+ns+", Expect: "+xs+", "+rms);
    }
    console.log(pass ? "PASS!" : "FAIL!");
}

I also reran the benchmark with function #8 added to the list. I won't post the result, as they're a bit embarrassing (e.g. that function is NOT fast)...

The (abridged -- I removed successful tests, since the output is quite long) results are as follows:

Testing function 0
Value: (object) [object Array], Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (boolean) true, Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (boolean) false, Expect: (boolean) false, Result: (boolean) true, Match: false
Value: null, Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (string) '', Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (string) '1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '-1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
FAIL!

Testing function 1
Value: (string) '1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
PASS!

Testing function 2
Value: (string) '1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
PASS!

Testing function 3
Value: (object) true, Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (object) false, Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (boolean) [object Array], Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (boolean) [object Object], Expect: (boolean) false, Result: (boolean) true, Match: false
Value: null, Expect: (boolean) false, Test skipped; function threw exception!
Value: (string) '', Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (string) 'a', Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (string) '1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '-1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
FAIL!

Testing function 4
Value: (string) '1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
PASS!

Testing function 5
Value: (string) '1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
PASS!

Testing function 6
Value: null, Expect: (boolean) false, Test skipped; function threw exception!
Value: (string) '1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '-1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
PASS!

Testing function 7
Value: (number) 1.1, Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (number) -1.1, Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (object) true, Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (boolean) [object Array], Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (boolean) [object Object], Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (string) '', Expect: (boolean) false, Result: (boolean) true, Match: false
Value: (string) '1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '-1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '1.1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '-1.1', Expect: (ANY), Result: (boolean) true, Match: N/A
FAIL!

Testing function 8
Value: (string) '1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '-1', Expect: (ANY), Result: (boolean) true, Match: N/A
Value: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
PASS!

Testing function 9
Value: (string) '1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
Value: (string) '-1.1', Expect: (ANY), Result: (boolean) false, Match: N/A
PASS!

I've left in failures so you can see where each function is failing, and the (string) '#' tests so you can see how each function handles integer and float values in strings, as some may want these parsed as numbers and some may not.

Out of the 10 functions tested, the ones that actually fit OP's requirements are [1,3,5,6,8,9]


We can check by isInteger function. ie number will return true and float return false

console.log(Number.isInteger(2)),<BR>

Will return true

console.log(Number.isInteger(2.5))

Will return false


try this one
function amountcheck()
    {
        var dpamt=$('#dpamt').val()/5000;
        var ints=dpamt.toString();
        var isint=ints.split('.');
        if(isint[1]>0)
        {
            alert('float value');
            return false;
        }
        else
        {   
            alert('int value');
        }
    }

Any Float number with a zero decimal part (e.g. 1.0, 12.00, 0.0) are implicitly cast to Integer, so it is not possible to check if they are Float or not.


It's simple as:

if( n === parseInt(n) ) ...

Try this in console:

x=1;
x===parseInt(x); // true
x="1";
x===parseInt(x); // false
x=1.1;
x===parseInt(x); // false, obviously

// BUT!

x=1.0;
x===parseInt(x); // true, because 1.0 is NOT a float!

This confuses a lot of people. Whenever something is .0, it's not a float anymore. It's an integer. Or you can just call it "a numeric thing" for there is no strict distinction like back then in C. Good old times.

So basically, all you can do is check for integer accepting the fact that 1.000 is an integer.

Interesting side note

There was a comment about huge numbers. Huge numbers mean NO problem for this approach; whenever parseInt is unable to handle the number (for it's too big) it will return something else than the actual value so the test will return FALSE. This is a good thing because if you consider something a "number" you normally expect JS to be able to calculate with it - so yes, numbers are limited and parseInt will take this into consideration, to put it this way.

Try this:

<script>

var a = 99999999999999999999;
var b = 999999999999999999999; // just one more 9 will kill the show!
var aIsInteger = (a===parseInt(a))?"a is ok":"a fails";
var bIsInteger = (b===parseInt(b))?"b is ok":"b fails";
alert(aIsInteger+"; "+bIsInteger);

</script>

In my browser (IE8) this returns "a is ok; b fails" which is exactly because of the huge number in b. The limit may vary but I guess 20 digits "ought to be enough for anybody", to quote a classical :)


function isInteger(x) { return typeof x === "number" && isFinite(x) && Math.floor(x) === x; }
function isFloat(x) { return !!(x % 1); }

// give it a spin

isInteger(1.0);        // true
isFloat(1.0);          // false
isFloat(1.2);          // true
isInteger(1.2);        // false
isFloat(1);            // false
isInteger(1);          // true    
isFloat(2e+2);         // false
isInteger(2e+2);       // true
isFloat('1');          // false
isInteger('1');        // false
isFloat(NaN);          // false
isInteger(NaN);        // false
isFloat(null);         // false
isInteger(null);       // false
isFloat(undefined);    // false
isInteger(undefined);  // false

parseInt(yourNumber)=== parseFloat(yourNumber)

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);
}

try this

let n;
return (n = value % 1) !== 0 && !isNaN(n);

when the return value is false means the input value is float number or float string, otherwise the input value is integer numbef or integer string.

basically it needs to check the precision value for not equal to zero.

another one is to check the correct string number also.


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!


THIS IS FINAL CODE FOR CHECK BOTH INT AND FLOAT

function isInt(n) { 
   if(typeof n == 'number' && Math.Round(n) % 1 == 0) {
       return true;
   } else {
       return false;
   }
} 

OR

function isInt(n) {   
   return typeof n == 'number' && Math.Round(n) % 1 == 0;   
}   

As others mentioned, you only have doubles in JS. So how do you define a number being an integer? Just check if the rounded number is equal to itself:

function isInteger(f) {
    return typeof(f)==="number" && Math.round(f) == f;
}
function isFloat(f) { return typeof(f)==="number" && !isInteger(f); }

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to types

Cannot invoke an expression whose type lacks a call signature How to declare a Fixed length Array in TypeScript Typescript input onchange event.target.value Error: Cannot invoke an expression whose type lacks a call signature Class constructor type in typescript? What is dtype('O'), in pandas? YAML equivalent of array of objects in JSON Converting std::__cxx11::string to std::string Append a tuple to a list - what's the difference between two ways? How to check if type is Boolean

Examples related to numbers

how to display a javascript var in html body How to label scatterplot points by name? Allow 2 decimal places in <input type="number"> Why does the html input with type "number" allow the letter 'e' to be entered in the field? Explanation on Integer.MAX_VALUE and Integer.MIN_VALUE to find min and max value in an array Input type "number" won't resize C++ - how to find the length of an integer How to Generate a random number of fixed length using JavaScript? How do you check in python whether a string contains only numbers? Turn a single number into single digits Python