How to tell if a string is a number in C #

Source: Internet
Author: User
Tags bool regular expression trim
String
  1. Regular expression
    string regex = @^\d+$;
  2. Write yourself a way: I wrote this.
    private bool Isnumber (string s)
    {
    int Flag = 0;
    Char[]str = S.tochararray ();
    for (int i = 0;i < str. Length; i++)
    {
    if (Char.isnumber (Str[i]))
    {
    flag++;
    }
    Else
    {
    Flag =-1;
    Break
    }
    }
    if (Flag > 0)
    {
    return true;
    }
    Else
    {
    return false;
    }
    }
  3. Test
    private void Button1_Click (object sender, System.EventArgs e)
    {
    if (Isnumber (TextBox1.Text.Trim ()))
    {
    TextBox2.Text = is a number;
    }
    Else
    {
    TextBox2.Text = not a number;
    }
  4. }
  5. Try
    {
    Double. Parse (this. TextBox1.Text);
    Response.Write (is a number);
    }
    Catch
    {
    Response.Write (not numbers);
    }
  6. Or you can use regular expressions:
  7. Using System.Text.RegularExpressions;
    ------------------------
  8. Regex r=new Regex (@^\d+ (\.)? \d*$);
    If R.ismatch (this. TextBox1.Text))
    {
    This. Response.Write (is a number);
    }
    Else
    {
    This. Response.Write (not numbers);
    }
  9. public static bool Strisint (string Str)
    {
    Try
    {
    Int32.Parse (STR);
    return true;
    }
    Catch
    {
    BOOL flag = FALSE;
    return flag;
    }
    }
  10. You should use regular expressions:
    String pattern = @^\d+ (\.\d)? $;
    if (Text1.Text.Trim ()!=)
    {
    if (! Regex.IsMatch (Sign_money. Text.trim (), pattern)
    {
    TEXT1 is not a number;
    }
    Else
    {
    Text1 is a number;
    }
    }


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.