How can I check if a string is a number?

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

    Starting with C# 7.0, you can declare the out variable in the argument list of the method call, rather than in a separate variable declaration. This produces more compact, readable code, and also prevents you from inadvertently assigning a value to the variable before the method call.

    bool isDouble = double.TryParse(yourString, out double result);
    

    https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/out-parameter-modifier

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

    use this

     double num;
        string candidate = "1";
        if (double.TryParse(candidate, out num))
        {
            // It's a number!
    
    
     }
    
    0 讨论(0)
  • 2020-11-27 21:32
    namespace Exception
    {
        class Program
        {
            static void Main(string[] args)
            {
                bool isNumeric;
                int n;
                do
                {
                    Console.Write("Enter a number:");
                    isNumeric = int.TryParse(Console.ReadLine(), out n);
                } while (isNumeric == false);
                Console.WriteLine("Thanks for entering number" + n);
                Console.Read();
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-27 21:34

    You should use the TryParse method for the int

    string text1 = "x";
        int num1;
        bool res = int.TryParse(text1, out num1);
        if (res == false)
        {
            // String is not a number.
        }
    
    0 讨论(0)
  • 2020-11-27 21:34

    The problem with some of the suggested solutions is that they don't take into account various float number formats. The following function does it:

    public bool IsNumber(String value)
    {
        double d;
        if (string.IsNullOrWhiteSpace(value)) 
            return false; 
        else        
            return double.TryParse(value.Trim(), System.Globalization.NumberStyles.Any,
                                System.Globalization.CultureInfo.InvariantCulture, out d);
    }
    

    It assumes that the various float number styles such es decimal point (English) and decima comma (German) are all allowed. If that is not the case, change the number styles paramater. Note that Any does not include hex mumbers, because the type double does not support it.

    0 讨论(0)
  • 2020-11-27 21:35
    int result = 0;
    bool isValidInt = int.TryParse("1234", out result);
    //isValidInt should be true
    //result is the integer 1234
    

    Of course, you can check against other number types, like decimal or double.

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