M G Vinod Kumar\’s Technology Blog

June 12, 2006

IsNumeric in C#

Filed under: .NET, Uncategorized — mgvinod @ 4:09 pm

C# doesn't have a IsNumeric or IsNumber on string object. So here are some implementations

Using Parse

public bool IsNumeric(string s)
{
      try
      {
            Int32.Parse(s);
      }
      catch
      {
            return false;
      }
      return true;
}
 

Using char 

internal static bool IsNumeric(string numberString)
{
    foreach (char c in numberString)
   {
        if (!char.IsNumber(c))
             return false;
   }
   return true;
}

Using Regex

static bool IsNumeric(string inputString)
{
    return Regex.IsMatch(inputString, "^[0-9]+$");
}

If you are using C# 2.0, you may use TryParse Method

public 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;

Advertisements

Create a free website or blog at WordPress.com.