How can I check if a string is a number?

后端 未结 25 1537
伪装坚强ぢ
伪装坚强ぢ 2020-11-27 21:04

I\'d like to know on C# how to check if a string is a number (and just a number).

Example :

141241   Yes
232a23   No
12412a   No

an

相关标签:
25条回答
  • 2020-11-27 21:13

    Many datatypes have a TryParse-method that will return true if it managed to successfully convert to that specific type, with the parsed value as an out-parameter.

    In your case these might be of interest:

    http://msdn.microsoft.com/en-us/library/system.int32.tryparse.aspx

    http://msdn.microsoft.com/en-us/library/system.decimal.tryparse.aspx

    0 讨论(0)
  • 2020-11-27 21:14
    Regex.IsMatch(stringToBeChecked, @"^\d+$")
    
    Regex.IsMatch("141241", @"^\d+$")  // True
    
    Regex.IsMatch("232a23", @"^\d+$")  // False
    
    Regex.IsMatch("12412a", @"^\d+$")  // False
    
    0 讨论(0)
  • 2020-11-27 21:15

    Perhaps you're looking for the int.TryParse function.

    http://msdn.microsoft.com/en-us/library/system.int32.tryparse.aspx

    0 讨论(0)
  • 2020-11-27 21:15

    Try This

    here i perform addition of no and concatenation of string

     private void button1_Click(object sender, EventArgs e)
            {
                bool chk,chk1;
                int chkq;
                chk = int.TryParse(textBox1.Text, out chkq);
                chk1 = int.TryParse(textBox2.Text, out chkq);
                if (chk1 && chk)
                {
                    double a = Convert.ToDouble(textBox1.Text);
                    double b = Convert.ToDouble(textBox2.Text);
                    double c = a + b;
                    textBox3.Text = Convert.ToString(c);
                }
                else
                {
                    string f, d,s;
                    f = textBox1.Text;
                    d = textBox2.Text;
                    s = f + d;
                    textBox3.Text = s;
                }
            }
    
    0 讨论(0)
  • 2020-11-27 21:16

    int.TryPasrse() Methode is the best way so if the value was string you will never have an exception , instead of the TryParse Methode return to you bool value so you will know if the parse operation succeeded or failed

    string yourText = "2";
    int num;
    bool res = int.TryParse(yourText, out num);
    if (res == true)
    {
        // the operation succeeded and you got the number in num parameter
    }
    else
    {
       // the operation failed
    }
    
    0 讨论(0)
  • 2020-11-27 21:17
    string str = "123";
    int i = Int.Parse(str);
    

    If str is a valid integer string then it will be converted to integer and stored in i other wise Exception occur.

    0 讨论(0)
提交回复
热议问题