none
How to check string is number or not in C#

    Question

  • Hi! Enveryone:

    I am new in C#. I want to check whether the user input to a text box is a number or not. What is the string function to check it? I do not want to use try and catch.

    Thank you very much!

    CLC

    Saturday, April 29, 2006 10:33 PM

Answers

  • If you are using the new .NET Framework 2.0 (C# 2005), then below code will work for you:


    string Str = textBox1.Text.Trim();

    double Num;

    bool isNum = double.TryParse(Str, out Num);

    if (isNum)

    MessageBox.Show(Num.ToString());

    else

    MessageBox.Show("Invalid number");


    Salan...

    Saturday, April 29, 2006 11:13 PM
  • Here's a nice implementation from the guys at sadeveloper.net:

    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;
        }
    }
    Sunday, April 30, 2006 7:34 AM

All replies

  • If you are using the new .NET Framework 2.0 (C# 2005), then below code will work for you:


    string Str = textBox1.Text.Trim();

    double Num;

    bool isNum = double.TryParse(Str, out Num);

    if (isNum)

    MessageBox.Show(Num.ToString());

    else

    MessageBox.Show("Invalid number");


    Salan...

    Saturday, April 29, 2006 11:13 PM
  •  

    In the TextBox_TextChange check the charater by using the following code

     

    for (int i=0; i<this.textbox1.text.length; i++)

    {

                   if (char.IsDigit(this.textbox1.textIdea)==false)

                                // give any error

    }

    Saturday, April 29, 2006 11:23 PM
  • This will not work if the user hits a character that is not a digit but it could be in a number like the dot '.' character or the negative/minus '-' character.


    Salan..
    Saturday, April 29, 2006 11:41 PM
  • If you're using .NET 1.1 then I like the following code...

    bool textIsNumeric = true;
    try
    {
    int.Parse(TextBox1.Text);
    }
    catch
    {
    textIsNumeric = false;
    }

    I know you said you didn't want to use try/catch but this is simple and effective.

    Sunday, April 30, 2006 6:32 AM
  • Here's a nice implementation from the guys at sadeveloper.net:

    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;
        }
    }
    Sunday, April 30, 2006 7:34 AM
  • Exceptions should be just that - exceptions.  Would you regard it as exceptional that an expression is passed to this routine that is not numeric?

    An IsNumeric in C# which does not rely on unexceptional exception logic is:http://www.tangiblesoftwaresolutions.com/Articles/CSharp%20Equivalent%20to%20IsNumeric.htm

     

    Sunday, April 30, 2006 1:21 PM
  • "Would you regard it as exceptional that an expression is passed to this routine that is not numeric?"

    No, which is exactly why I don't throw the exception. If an exception is caught, the string is obviously NOT numeric, and the method should return false. This is a perfectly acceptable case for not throwing an exception.

    Note that the example you posted will only work on .NET framework 2, where the TryParse methods are available.

    Sunday, April 30, 2006 1:26 PM
  • But within the method you are forcing an exception to occur when the expression is not numeric.  Forcing exceptions as part of normal logic flow when there is a more efficient alternative is something I wouldn't recommend.

    Double.TryParse is available in 1.1 (and 1.0 also).

    David Anton
    www.tangiblesoftwaresolutions.com
    Instant C#: VB to C# converter
    Instant VB: C# to VB converter
    Instant C++: C# to C++ converter and VB to C++ converter
    Instant J#: VB to J# converter
    Clear VB: Cleans up VB.NET code
    Clear C#: Cleans up C# code

    Sunday, April 30, 2006 1:34 PM
  • How am I "forcing" an exception?? I am in fact *preventing* an exception from being thrown.
    Yes, you're right! The TryParse method on double is available in framework 1.1.
    Sunday, April 30, 2006 1:36 PM
  • Within your method, an exception occurs for most cases where the expression is not numeric.  You catch the exception within the method.  The fact that you don't throw the exception further is not the issue.

    Run a test with both methods and you'll see that with relatively few iterations, the one that relies on exceptions is very slow when the expression is not numeric.  For example, at fewer than 100 iterations you can see an obvious difference.  If you have this "unexceptional exception" approach throughout your code, you will have performance issues.

    David Anton
    www.tangiblesoftwaresolutions.com
    Instant C#: VB to C# converter
    Instant VB: C# to VB converter
    Instant C++: C# to C++ converter and VB to C++ converter
    Instant J#: VB to J# converter
    Clear VB: Cleans up VB.NET code
    Clear C#: Cleans up C# code

    Sunday, April 30, 2006 1:50 PM
  • Ah, I see what you mean. Sure, the creation of the exception (by Double.Parse) would be expensive.
    Without using TryParse, however, this is the only way I can see it happening.
    Sunday, April 30, 2006 2:09 PM
  • That's why double.TryParse is a good option.
    Sunday, April 30, 2006 2:28 PM
  • Hi!
    Thanks for all of you.
    I tried it and it solve my problem. In  .Net 1.1, Double.TryParse use four paremeters so follows:
    Double.TryParse(Str, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.CurrentCulture, out Num)

    Thank again!

    CLC
    Monday, May 01, 2006 6:01 AM
  • Yip, it's the best way
    Monday, May 01, 2006 12:17 PM
  • Why not doing something simple and validating the string with a regular expression?

    bool IsNumber(string text)
    {
     
    Regex regex = new Regex(@"^[-+]?[0-9]*\.?[0-9]+$");
     
    return regex.IsMatch(text);
    }

    • Proposed as answer by EdwardT.Drew Sunday, May 02, 2010 11:50 PM
    Monday, May 01, 2006 6:27 PM
  • With some fine-tuning, that would work well also.

    But why do you think it's easier than a call to double.TryParse?

    David Anton
    www.tangiblesoftwaresolutions.com
    Instant C#: VB to C# converter
    Instant VB: C# to VB converter
    Instant C++: C# to C++ converter and VB to C++ converter
    Instant J#: VB to J# converter
    Clear VB: Cleans up VB.NET code
    Clear C#: Cleans up C# code

    Monday, May 01, 2006 6:40 PM
  • To validate a string it is more generic and you can cover more exotic cases, too, e.g. -45.56% and so forth... I would prefer it, because one can use the same concept of string validation all over to validate more cases, not only numbers.
    Monday, May 01, 2006 9:12 PM
  •  

    For those seeking completion;

     

    /// <summary>

    /// Mimics Visual Basics IsNumeric functionality so we don't have to include there library for this one function.

    /// </summary>

    /// <param name="MayBeANum">Anything. Hopefully something that can be parsed into a number.</param>

    /// <returns></returns>

    /// <remarks>

    /// Alternative:

    /// <para>Pattern matching using a regular expression is a very flexible solution, and is especially useful if you

    /// need to test for very large numbers that might be too big to fit in a variable. </para>

    /// <code>

    /// string strToTest = "123";

    /// Regex reNum = new Regex(@"^\d+$");

    /// bool isNumeric = reNum.Match(strToTest).Success;

    /// </code>

    /// <para>

    /// This pattern will evaluate true for any non-negative integer. You could adapt the regular expression to include

    /// any number format you want, such as negative, decimal or even complex numbers.</para>

    /// </remarks>

    public static bool IsNumeric(object MayBeANum)

    {

    if (IsNullOrEmpty(MayBeANum)) //null should be considered zero only if this was a conversion routine

    return false;

    double number;

    // System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo("en-US", true);

    return Double.TryParse(Convert.ToString(MayBeANum, CultureInfo.InvariantCulture),

    System.Globalization.NumberStyles.Any, NumberFormatInfo.InvariantInfo, out number);

    }

    Thursday, September 13, 2007 2:52 PM
  • Thanks Salan!
    This solution worked for me.
    Wednesday, February 27, 2008 8:16 AM

  • Do this way:

    int num;
    bool isNumeric = int.TryParse(txtNum.text, out num);
    if(isNumeric)
    {
    // Do your code, the value is number
    }
    else
    {
    // value is not a number
    }



    change int with double or others as per your need.
    enjoy coding....

    Please mark as answer, if you satisfied with this code sample.

    -- K



    Monday, March 17, 2008 11:33 AM
  •  

    Well, methods like int.TryParse should work for most values used in real life, however if the textbox contained a number higher than the maximum number than an int can contain it would fail, although it could still be a number.

     

    so i suggest using the char.IsNumber method (as long as u are sure that the input value will not conatin (+ or - chars) or it will not be exponent value.

     

    every methods has its drawbacks.

     

    example:

     

    Code Snippet

    public static bool IsNumeric(string NumericText)

    {

    bool isnumber = true;

    foreach(char c in NumericText)

    {

    isnumber = char.IsNumber(c);

    if (!isnumber)

    {

    return isnumber;

    }

    }

    return isnumber;

    }

     

     

     

    Monday, March 17, 2008 11:49 AM

  • Hi,

    if it doesnot take any +/- then how it can be helpfull???
    in any case, it may require that + or - is require............. at that time??? think...

    -- K


    Monday, March 17, 2008 12:09 PM
  •  

    string.Strtswith('+') and  string.Startswith('-') should solve it
    Monday, March 17, 2008 12:22 PM
  • What is the lightbulb there supposed to represent?
    Tuesday, October 07, 2008 2:14 AM
  • Hi All,


    You can refer this link.....

    http://abansal.wordpress.com/

    Thanks.
    • Proposed as answer by Amit Bansal Wednesday, November 11, 2009 9:48 AM
    Tuesday, October 07, 2008 5:01 AM
  •  

    Nice Post,

     

    I got Exactly I was looking for !!!

     

    Thanks.

    Tuesday, October 07, 2008 8:00 AM
  • 1. Why are you even in this forum?

    2. PHP is old and not as scalable as .Net.

    3. Because PHP is open source does allow for compiling into DLL's which is less efficient for the web server and apache has to code-check on every pass.

    5. Yes, PHP is more like old VB and has some simplified methods. But compared to VB.NET and C#.NET is again not as scalable and efficient.

    So stick with PHP forums. Your “.NET is very bad (((” comment is a waste time for those who seek suggestions in their relevant language. 

     

    The big question is why are you here?  I guess you just think you’re the “ultimate smarty pants.”  Take your superior intelligence to the land of PHP where your pious-smugness can be exercised to its full capacity and leave us alone.

     

    Bet you think you’re the ultimate coder and better than everyone else. So congratulations and go away.

     

     

    Friday, April 01, 2011 9:05 PM
  • Why not doing something simple and validating the string with a regular expression?

    bool IsNumber(string text)
    {
     
    Regex regex = new Regex(@"^[-+]?[0-9]*\.?[0-9]+$");
     
    return regex.IsMatch(text);
    }

     The above solution is working fine...... I have tested... Thanking you so much....
    Wednesday, April 20, 2011 3:24 PM
  • Regular expressions are indeed more efficient.

    So to catch all number-like string expressions, including currency,decimal- and thousand separators, and decimal fractions, use the following:

    Private Function IsNumber(word As StringAs Boolean
    
     Return Regex.IsMatch(word, "^-?\d*[0-9]?(|.\d*[0-9]|,\d*[0-9])?$")
    
    End Function


    Saturday, April 30, 2011 9:26 PM
  • just Implement the KeyPress event of the textbox and write these codes

    private void Textbox1_KeyPress(object sender , KeyPressEventArg e)

    {

          if(char.isControl(e.keyChar) || char.IsDigit(e.KeyChar))

             e.handle = false;

          else

            e.handle = true;

    }

     

    textbox just will get number 

     

    please mark it as answer when you reach your goal

     

    Sunday, May 01, 2011 4:19 AM
  • Here is a concise implementation from Microsoft.

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

    See http://support.microsoft.com/kb/329488

    • Proposed as answer by PreabSor Saturday, October 15, 2011 9:54 AM
    • Unproposed as answer by PreabSor Saturday, October 15, 2011 9:54 AM
    Thursday, October 13, 2011 4:50 PM
  • Stormjack: I'm sorry about proposed, mouse mistake.

    Hi all,

    You all are the best. Thank for your all answer. :)

    Saturday, October 15, 2011 10:04 AM
  • Hi,

    Any particular reason for not using try{} catch{} block?

    I had the same requirement to validate the text entered in a text box is number. I used try-catch block and it saved me rather writing my own logic to find whether the entered text is number or not.

    Thanks,
    Soubram 

    Monday, December 19, 2011 9:33 AM
  • Hi,

    Any particular reason for not using try{} catch{} block?

    I had the same requirement to validate the text entered in a text box is number. I used try-catch block and it saved me rather writing my own logic to find whether the entered text is number or not.

    Thanks,
    Soubram 


    catch is expensive to handle and as Dave Doknja points out should only be used to capture true unexpected exceptions. A quick google search will provide details as to why and should generally be avoided if the catch case is likely to occur or if there are other means of checking for the null case like using an if/else conditional instead.
    Thursday, January 19, 2012 3:25 AM
  • hi,

    Can we use this for web development instead?

    tnaks

    Thursday, May 10, 2012 10:29 AM
  • public static bool IsConvertable (System.Object pExpression, Type pType ) { if (pExpression.GetType()== pType) return true; try { Convert.ChangeType(pExpression, pType); return true; } catch { } return false; }

    Reusable function to check conversion cases.

    Handles Null Object Numeric and Overflow.

    Wednesday, June 27, 2012 8:25 AM
  • I like it but what are you using as a library if it is not form but web and ...aspx.cs

    in this example using System.Windows.Forms cannot work?

    and you are using KeyPressEventArg what is not at library.


    Wednesday, September 12, 2012 4:25 PM
  • This doesn't work if you ever plan to support international languages. The word as String variable is evaluated as a CComBSTR in C++ lingo. So if the user sets the language to Arabic, then the word variable will contain unicode Arabic characters, and will fail every time!

    http://www.SethEden.com

    Friday, October 05, 2012 4:04 PM
  • brackets mismatch I made little correction...

    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);
                        return true;
                    }
                    else
                    {
                        Double.Parse(Expression.ToString());
                        return true;
                    }  
    
                }
                catch (Exception ex)
                {
                    return false;
                }
            }

    Monday, November 12, 2012 2:43 PM
  • Regular expressions are indeed more efficient.

    So to catch all number-like string expressions, including currency,decimal- and thousand separators, and decimal fractions, use the following:

    Private Function IsNumber(word As StringAs Boolean
    
     Return Regex.IsMatch(word, "^-?\d*[0-9]?(|.\d*[0-9]|,\d*[0-9])?$")
    
    End Function


    You'll still have to make that international though. Cause 1000.00,00 might be written as 1000,00.00
    Wednesday, November 14, 2012 1:32 PM
  • These numeric types should also be included.

    || Expression is Byte || Expression is SByte || Expression is UInt32  || Expression is UInt64  || Expression is UInt16

    Saturday, January 05, 2013 10:35 PM
  • Throwing and catching the exception comes at a considerable cost, which is why you should just check each digit.
    Monday, July 22, 2013 9:55 AM
  • Regular expressions are relatively costly.
    Monday, July 22, 2013 9:56 AM
  • simply try return str.All(Char.IsDigit);
    Wednesday, October 23, 2013 5:49 AM