How can I check if a string is a number?

后端 未结 25 1539
伪装坚强ぢ
伪装坚强ぢ 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:18

    Yes there is

    int temp;
    int.TryParse("141241", out temp) = true
    int.TryParse("232a23", out temp) = false
    int.TryParse("12412a", out temp) = false
    

    Hope this helps.

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

    You could use something like the following code:

        string numbers = "numbers you want to check";
    
        Regex regex = new Regex("^[0-9]+$"));
    
        if (regex.IsMatch(numbers))
        {
            //string value is a number
        }
    
    0 讨论(0)
  • 2020-11-27 21:25

    This is my personal favorite

    private static bool IsItOnlyNumbers(string searchString)
    {
    return !String.IsNullOrEmpty(searchString) && searchString.All(char.IsDigit);
    }
    
    0 讨论(0)
  • 2020-11-27 21:26

    If you just want to check if a string is all digits (without being within a particular number range) you can use:

    string test = "123";
    bool allDigits = test.All(char.IsDigit);
    
    0 讨论(0)
  • 2020-11-27 21:26

    Use int.TryParse():

    string input = "141241";
    int ouput;
    bool result = int.TryParse(input, out output);
    

    result will be true if it was.

    0 讨论(0)
  • 2020-11-27 21:26
    int value;
    if (int.TryParse("your string", out value))
    {
        Console.WriteLine(value);
    }
    
    0 讨论(0)
提交回复
热议问题