Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lorenzoongithub/a3c46f837ea7bbb708ae to your computer and use it in GitHub Desktop.
Save lorenzoongithub/a3c46f837ea7bbb708ae to your computer and use it in GitHub Desktop.
how to check if a variable is an integer in javascript
//
// four different ways to check if a variable is an integer
// from stackoverflow
// http://stackoverflow.com/questions/14636536/how-to-check-if-a-variable-is-an-integer-in-javascript
//
//Raw solution
function isInt1(value) {
return !isNaN(value) && parseInt(Number(value)) == value && !isNaN(parseInt(value, 10));
}
// Bitwise
// Simple parse and check
function isInt2(value) {
var x = parseFloat(value);
return !isNaN(value) && (x | 0) === x;
}
// Short-circuiting, and saving a parse operation
function isInt3(value) {
if (isNaN(value)) {
return false
}
var x = parseFloat(value);
return (x | 0) === x
}
// Both in one shot
function isInt4(value) {
return !isNaN(value) && (function(x) { return (x | 0) === x; })(parseFloat(value))
}
// Testing:
if (isInt1(42) != true) throw '';
if (isInt1("42") != true) throw '';
if (isInt1(4e2) != true) throw '';
if (isInt1("4e2")!= true) throw '';
if (isInt1(" 1 ")!= true) throw '';
if (isInt1("")) throw '';
if (isInt1(" ")) throw '';
if (isInt1(42.1)) throw '';
if (isInt1(null)) throw '';
if (isInt1(NaN)) throw '';
if (isInt1("1 a")) throw '';
if (isInt1("4e2a")) throw '';
if (isInt2(42) != true) throw '';
if (isInt2("42") != true) throw '';
if (isInt2(4e2) != true) throw '';
if (isInt2("4e2")!= true) throw '';
if (isInt2(" 1 ")!= true) throw '';
if (isInt2("")) throw '';
if (isInt2(" ")) throw '';
if (isInt2(42.1)) throw '';
if (isInt2(null)) throw '';
if (isInt2(NaN)) throw '';
if (isInt2("1 a")) throw '';
if (isInt2("4e2a")) throw '';
if (isInt3(42) != true) throw '';
if (isInt3("42") != true) throw '';
if (isInt3(4e2) != true) throw '';
if (isInt3("4e2")!= true) throw '';
if (isInt3(" 1 ")!= true) throw '';
if (isInt3("")) throw '';
if (isInt3(" ")) throw '';
if (isInt3(42.1)) throw '';
if (isInt3(null)) throw '';
if (isInt3(NaN)) throw '';
if (isInt3("1 a")) throw '';
if (isInt3("4e2a")) throw '';
if (isInt4(42) != true) throw '';
if (isInt4("42") != true) throw '';
if (isInt4(4e2) != true) throw '';
if (isInt4("4e2")!= true) throw '';
if (isInt4(" 1 ")!= true) throw '';
if (isInt4("")) throw '';
if (isInt4(" ")) throw '';
if (isInt4(42.1)) throw '';
if (isInt4(null)) throw '';
if (isInt4(NaN)) throw '';
if (isInt4("1 a")) throw '';
if (isInt4("4e2a")) throw '';
@egoroof
Copy link

egoroof commented Jan 1, 2016

Number.isInteger(val);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment