Microsoft Most Valuable Professional

Chris Pietschmann

An MVP From Wisconsin



JavaScript int.TryParse Equivalent

One of the most handy methods in .NET is the int.TryParse method. It makes it really convenient when evaluating a string value as an integer. But, JavaScript has no equivalent so you need to do your own evaluation every time.

Here's a simple JavaScript method I wrote that takes the work out of evaluating a string to an integer:

The first parameter of the TryParseInt method is the string you want to evaluate, and the second parameter is the default value to return if the string cannot be evaluated to an integer.

Here are some example usages:

Currently rated 5.0 by 2 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: General
Posted by crpietschmann on Monday, January 14, 2008 9:47 PM
Permalink | Comments (1) | Post RSSRSS comment feed

Related posts

Comments

Björn Graf

Tuesday, January 15, 2008 6:03 AM

Björn Graf

... isNaN("") == false and parseInt("") == NaN...

So, a better test would be (null and undefined values of str will result in false):
function TryParseInt(str, defaultValue) {
return /^\d+$/.test(str) ? parseInt(str) : defaultValue;
}

Comments are closed

About the author

I'm Chris Pietschmann, go to the About Me page to learn more about me.

Search

Sponsors

Web.Maps.VE - ASP.NET AJAX Virtual Earth Mapping Server Control

Recent comments

Disclaimer


This work is licensed under a Creative Commons Attribution 3.0 United States License, unless explicitly stated otherwise within the posted content.
© Copyright 2004 - 2008 Chris Pietschmann