0

I am searching the ultimate best way to check if a var is a Number

function isInt(n){ 
   return !isNaN(parseInt(n * 1));
}

alert(isInt(""));//true

This website lied to me http://www.inventpartners.com/content/javascript_is_int

and the second comment of a guy of the anser https://stackoverflow.com/a/3886106/908879 scared me enough to don't use his answer

please help me to find the correct one plxplx

Community
  • 1
  • 1
ajax333221
  • 11,436
  • 16
  • 61
  • 95

4 Answers4

3

The following could be a pretty good solution to your problem. However this returns false if it is a floating point number

function isInt(n){ 
    return !isNaN(parseFloat(n)) && isFinite(n) && (n % 1 == 0); 
};

If you want to know if it is in general a number the best solution is

function isNumber(n){ 
    return !isNaN(parseFloat(n)) && isFinite(n); 
};

See also: http://dl.dropbox.com/u/35146/js/tests/isNumber.html

fyr
  • 20,227
  • 7
  • 37
  • 53
0

There are faster-running solutions if you want speed.

function isInt(v) { return v === ~~v; }
function isNumber(v) { return v === +v; }
function isNumeric(v) { return v === +v || v === +v + ''; }
function isIntLike(v) { return v === ~~v || v === ~~v + ''; }

All relevant checks can be defined with no function-calls.

Note that NaN !== NaN, so no isNaN call is required.

Keen
  • 954
  • 12
  • 19
0

if you only want to know n is a Number,you can use:

function isNumber(n){
    return typeof n == 'number';
}
alert(isNumber(""));//false
artwl
  • 3,502
  • 6
  • 38
  • 53
0

You may have to do a bit more checking:

function isInt(n){ 
 n = Number(n);
 return String(n).length 
        && !isNaN(parseInt(n,10)) 
        && n%1 === 0;
}
KooiInc
  • 119,216
  • 31
  • 141
  • 177