[c#] How to check if IsNumeric

Possible Duplicate:
How to identify if string contain a number?

In VB there's an IsNumeric function, is there something similar in c#?

To get around it, I just wrote the code:

    if (Int32.Parse(txtMyText.Text.Trim()) > 0)

I was just wondering if there is a better way to do this.

This question is related to c#

The answer is


You should use TryParse - Parse throws an exception if the string is not a valid number - e.g. if you want to test for a valid integer:

int v;
if (Int32.TryParse(textMyText.Text.Trim(), out v)) {
  . . .
}

If you want to test for a valid floating-point number:

double v;
if (Double.TryParse(textMyText.Text.Trim(), out v)) {
  . . .
}

Note also that Double.TryParse has an overloaded version with extra parameters specifying various rules and options controlling the parsing process - e.g. localization ('.' or ',') - see http://msdn.microsoft.com/en-us/library/3s27fasw.aspx.


There's the TryParse method, which returns a bool indicating if the conversion was successful.


There's a slightly better way:

int valueParsed;
if(Int32.TryParse(txtMyText.Text.Trim(), out valueParsed))
{ ... }

If you try to parse the text and it can't be parsed, the Int32.Parse method will raise an exception. I think it is better for you to use the TryParse method which will capture the exception and let you know as a boolean if any exception was encountered.

There are lot of complications in parsing text which Int32.Parse takes into account. It is foolish to duplicate the effort. As such, this is very likely the approach taken by VB's IsNumeric. You can also customize the parsing rules through the NumberStyles enumeration to allow hex, decimal, currency, and a few other styles.

Another common approach for non-web based applications is to restrict the input of the text box to only accept characters which would be parseable into an integer.

EDIT: You can accept a larger variety of input formats, such as money values ("$100") and exponents ("1E4"), by specifying the specific NumberStyles:

int valueParsed;
if(Int32.TryParse(txtMyText.Text.Trim(), NumberStyles.AllowCurrencySymbol | NumberStyles.AllowExponent, CultureInfo.CurrentCulture, out valueParsed))
{ ... }

... or by allowing any kind of supported formatting:

int valueParsed;
if(Int32.TryParse(txtMyText.Text.Trim(), NumberStyles.Any, CultureInfo.CurrentCulture, out valueParsed))
{ ... }

You should use TryParse method which Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the conversion succeeded.

    int intParsed;
    if(int.TryParse(txtMyText.Text.Trim(),out intParsed))
    {
        // perform your code
    }

Other answers have suggested using TryParse, which might fit your needs, but the safest way to provide the functionality of the IsNumeric function is to reference the VB library and use the IsNumeric function.

IsNumeric is more flexible than TryParse. For example, IsNumeric returns true for the string "$100", while the TryParse methods all return false.

To use IsNumeric in C#, add a reference to Microsoft.VisualBasic.dll. The function is a static method of the Microsoft.VisualBasic.Information class, so assuming you have using Microsoft.VisualBasic;, you can do this:

if (Information.IsNumeric(txtMyText.Text.Trim())) //...

I think you need something a bit more generic. Try this:

public static System.Boolean IsNumeric (System.Object Expression)
{
    if(Expression == null || Expression is DateTime)
        return false;

    if(Expression is Int16 || Expression is Int32 || Expression is Int64 || Expression is Decimal || Expression is Single || Expression is Double || Expression is Boolean)
        return true;

    try 
    {
        if(Expression is string)
            Double.Parse(Expression as string);
        else
            Double.Parse(Expression.ToString());
            return true;
        } catch {} // just dismiss errors but return false
        return false;
    }
}

Hope it helps!


You could write an extension method:

public static class Extension
{
    public static bool IsNumeric(this string s)
    {
        float output;
        return float.TryParse(s, out output);
    }
}