isInt() JavaScript function


22nd of May 2006

Here's my take on a function that determines if a variable is an integer or not before or after it's been recast to an int. The functionality is very similar to Python's isdigit() function which works like this:

 >>> assert "1".isdigit()
 >>> assert not "1.0".isdigit()

However, my Javascript function should return true when the input is an integer or a string of an integer. Here it goes:

 function isInt(x) {
   var y=parseInt(x);
   if (isNaN(y)) return false;
   return x==y && x.toString()==y.toString();
 }
 assert(isInt("1"));
 assert(isInt(1));
 assert(!isInt("1a"));
 assert(!isInt("1.0"));

You can see it in action here. To be honest, I'm writing about this here just to not forget it the next time I need a similar function. Sorry to cause any interweb-noise.



Comment

Show all 13 comments
 
Name:
Email:
hide my email address.

Your email address will be encoded to prevent email-extraction spiders from reading it so you won't get spammed if you decide to show your email address.