Kung Fu Kung Fu

Fujian White Crane Kung Fu

Zope Zope

What I have and am doing with Zope

Photos Photos

Photoalbum, both old and new.

Receptsamlingen Receptsamlingen

In Swedish only. About my "Collection of Recipes" website.

Contact me Contact me

My contact details and how to contact me.

  Mobile version of this page Mobile version of this page


 

isInt() JavaScript function

assert, isdigit, isnan, tostring, parseint, isint, integer, int

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

Manuel SIMONOT - 26th May 2006  [«« Reply to this]
Thanx good idea i think. But are you sure the second part of the condition is useful?

Not sure:p
Peter Bengtsson - 31st May 2006   [«« Reply to this]
The second part is necessary so that "1.0" yields a false.
Anonymous - 31st May 2006   [«« Reply to this]
Indeed. My mistake:s
Kal - 16th April 2007  [«« Reply to this]
Am I allowed to use this function as long as I give you credit for it in my source code?
Okonomiyaki3000 - 11th December 2007  [«« Reply to this]
how about this:

String.prototype.isInt = function()
{
var re = new RegExp("^[\d]+$");
return this.match(re);
}
marchaos - 19th January 2008   [«« Reply to this]
that will fail for negative numbers.
Anonymous - 18th January 2008  [«« Reply to this]
assert -> alert
 
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.