Creating a IsNumeric Function in C#

Posted: July 2, 2011 in ASP.Net

In Visual C#, you can use the Double.TryParse method to obtain functionality that is similar to IsNumeric. Double.TryParse converts the string representation of a number in a specified style and culture-specific format to its double-precision floating point number equivalent. Create a function as follows:

static bool IsNumeric(object Expression)
{
  bool isNum;
  double retNum;
  isNum = Double.TryParse(Convert.ToString(Expression), System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, out retNum);
  return isNum;
}

So now you can use it as follows:

// When value is numeric
if (IsNumeric("123"))
{
  // ...
}

// When value is not numeric
if (!IsNumeric("ABC"))
{
  // ...
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s