To check whether the string value has numeric value or not in C#

后端 未结 8 2268
你的背包
你的背包 2021-02-14 02:29

I am having an string like this

string str = \"dfdsfdsf8fdfdfd9dfdfd4\"

I need to check whether the string contains number by looping through the array.

8条回答
  •  自闭症患者
    2021-02-14 02:55

    If you are looking for an integer value you could use int.TryParse:

    int result;
    if (int.TryParse("123", out result))
    {
        Debug.WriteLine("Valid integer: " + result);
    }
    else
    {
        Debug.WriteLine("Not a valid integer");
    }
    

    For checking a decimal number, replace int.TryParse with Decimal.TryParse. Check out this blog post and comments "Why you should use TryParse() in C#" for details.

    If you need decimal numbers, you could alternatively use this regular expression:

    return System.Text.RegularExpressions.Regex.IsMatch(
       TextValue, @"^-?\d+([\.]{1}\d*)?$");
    

    And finally another alternative (if you are not religiously against VB.NET), you could use the method in the Microsoft.VisualBasic namespace:

    Microsoft.VisualBasic.Information.IsNumeric("abc"); 
    

提交回复
热议问题