Posts tagged with IsNumeric

C# IsNumeric

October 28th, 2009

If you do a search for ‘C# IsNumeric’ you’ll find a lot of hits talking about why this function is available in VB.NET but not in C#.NET. It’s used to test if a given string can be converted to a number.

I agree it’s a very useful function and there’s lots of possible solutions, the main ones being

  1. Loop through the string and check each Char is a number
  2. Use Double.TryParse is a very popular one since it doesn’t throw an exception on failure
  3. Use Convert.ToInt32 inside a try/catch block
  4. Using a Regex expression

I really wanted to use Double.TryParse but unfortunately this will return true for numbers that are decimals. Therefore if you want to test a string for whole numbers you also have to check the string for periods or commas (using string.contains) depending on your locale.

For this reason I tend to use the Regex solution, mainly because it’s very short and simple to implement.

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

It also requires the using directive System.Text.RegularExpressions

Google BookmarksEvernoteGoogle GmailHotmailWordPressLinkedInFacebookDeliciousShare

Switch to our mobile site