views:

488

answers:

10

One thing that has bothered me about C# since its release was the lack of a generic IsNumeric function. I know it is difficult to generate a one-stop solution to detrmine if a value is numeric.

I have used the following solution in the past, but it is not the best practice because I am generating an exception to determine if the value is IsNumeric:

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

Is this still the best way to approach this problem or is there a more efficient way to determine if a value is numeric in C#?

+7  A: 

Rather than using int.Parse, you can use int.TryParse and avoid the exception.

Something like this

public static bool IsNumeric(string input)
{
  int dummy;
  return int.TryParse(input, out dummy);
}

More generically you might want to look at double.TryParse.

One thing you should also consider is the potential of handling numeric string for different cultures. For example Greek (el-GR) uses , as a decimal separator while the UK (en-GB) uses a .. So the string "1,000" will either be 1000 or 1 depending on the current culture. Given this, you might consider providing overloads for IsNumeric that support passing the intended culture, number format etc. Take a look at the 2 overloads for double.TryParse.

Chris Taylor
+15  A: 

Try this:

int temp;
return int.TryParse(input, out temp);

Of course, the behavior will be different from Visual Basic IsNumeric. If you want that behavior, you can add a reference to "Microsoft.VisualBasic" assembly and call the Microsoft.VisualBasic.Information.IsNumeric function directly.

Mehrdad Afshari
I would use `decimal` or `double`, because lots of things are numeric but not integers.
Gabe
@Gabe: Yeah, in general case; but the OP seems to be specifically looking for `int`.
Mehrdad Afshari
If it's specific for int, I would change the method name to IsInteger.
bloparod
Thanks. Any value that contains numeric values, including leading zeros, passes.
Michael Kniskern
+3  A: 

If you use Int32.TryParse then you don't need to wrap the call in a TryCatch block, but otherwise, yes that is the approach to take.

Walter
+1  A: 

Take a look on the following answer: http://stackoverflow.com/questions/437882/c-equivalent-of-nan-or-isnumeric

Double.TryParse takes care of all numeric values and not only ints.

Klinger
A: 
public bool IsNumeric(string input)
{
   int result;
   return Int32.TryParse(input,out result);
}
Alan
A: 

try this:

public static bool IsNumeric(object o)
{
    const NumberStyles sty = NumberStyles.Any;
    double d;
    return (o != null && Double.TryParse(o.ToString(), sty, null, out d));
}
Charles Bretana
epic fail if o is null!
John Buchanan
Charles Bretana
+11  A: 

You can use extension methods to extend the String type to include IsNumeric:

namespace ExtensionMethods
{
    public static class MyExtensions
    {
        public static bool IsNumeric(this String str)
        {
             int temp;
             return int.TryParse(input, out temp);        
        }
    }   
}
Eric J.
+3  A: 

Not exactly crazy about this approach, but you can just call the vb.net isNumeric function from C# by adding a reference to the Microsoft.VisualBasic.dll library...

bool x= Microsoft.VisualBasic.Information.IsNumeric("123");

The other approaches given are superior, but wanted to add this for the sake of completeness.

JohnFx
+1 For being brave enough to add it!
Walter
+3  A: 

I've used the following extension method before, if it helps at all:

public static int? AsNumeric(this string source)
{
  int result;
  return Int32.TryParse(source, out result) ? result : (int?)null;
}

Then you can use .HasValue for the bool you have now, or .Value for the value, but convert just once...just throwing it out there, not sure what situation you're using it for afterwards.

Nick Craver
Ha, typed an answer like this, just noticed you put up a more complete solution 3 minutes before me. I definitely question the discarding of a conversion result since it seems likely it will be needed soon if the string is numeric.
jball
+1  A: 

Lot's of TryParse answers. Here's something a bit different using Char.IsNumber():

    public bool IsNumeric(string s)
    {
        for (int i = 0; i < s.Length; i++)
        {
            if (char.IsNumber(s, i) == false)
            {
                return false;
            }
        }
        return true;
    }
Paul Kearney - pk
I also like this solution.
Michael Kniskern