【问题标题】:Check string for only digits and one optional decimal point.仅检查字符串中的数字和一个可选的小数点。
【发布时间】:2010-01-19 09:37:58
【问题描述】:

我需要检查一个字符串是否只包含数字。我如何在 C# 中实现这一点?

string s = "123"    → valid 
string s = "123.67" → valid 
string s = "123F"   → invalid 

有没有类似 IsNumeric 的函数?

【问题讨论】:

    标签: c# numeric


    【解决方案1】:
    double n;
    if (Double.TryParse("128337.812738", out n)) {
      // ok
    }
    

    假设数字不会溢出双倍

    对于一个巨大的字符串,试试正则表达式:

    if (Regex.Match(str, @"^[0-9]+(\.[0-9]+)?$")) {
      // ok
    }
    

    如果需要,添加科学记数法 (e/E) 或 +/- 符号...

    【讨论】:

    • 参数应该是什么?它会接受一个巨大的字符串吗?有什么限制吗?
    • 对于一个巨大的字符串,你需要一个正则表达式
    • 不应该是Regex.IsMatch(),它返回一个bool,而不是Match(),它返回一个Match?
    • @imoatama 感谢您为我修复的附加评论
    【解决方案2】:

    取自MSDN(如何使用 Visual C# 实现 Visual Basic .NET IsNumeric 功能):

    // IsNumeric Function
    static bool IsNumeric(object Expression)
    {
        // Variable to collect the Return value of the TryParse method.
        bool isNum;
    
        // Define variable to collect out parameter of the TryParse method. If the conversion fails, the out parameter is zero.
        double retNum;
    
        // The TryParse method converts a string in a specified style and culture-specific format to its double-precision floating point number equivalent.
        // The TryParse method does not generate an exception if the conversion fails. If the conversion passes, True is returned. If it does not, False is returned.
        isNum = Double.TryParse(Convert.ToString(Expression), System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, out retNum );
        return isNum;
    }
    

    【讨论】:

      【解决方案3】:

      您可以使用double.TryParse

      string value;
      double number;
      
      if (Double.TryParse(value, out number))
         Console.WriteLine("valid");
      else
         Console.WriteLine("invalid");
      

      【讨论】:

        【解决方案4】:

        无论字符串有多长,这都应该有效:

        string s = "12345";
        bool iAllNumbers = s.ToCharArray ().All (ch => Char.IsDigit (ch) || ch == '.');
        

        【讨论】:

        • 这也将匹配“123.456.789”,这是一个无效的数字
        • @Philippe:你是对的。我认为 RegExp 是最干净的方式。
        • @Tarydon System.Array 不包含 All 的定义?!
        【解决方案5】:

        使用正则表达式是最简单的方法(但不是最快的):

        bool isNumeric = Regex.IsMatch(s,@"^(\+|-)?\d+(\.\d+)?$");
        

        【讨论】:

        • 您缺少.23 案例。
        • 可能,如果您想允许 Commodore 64 计算机 25 年前使用的数字 :-)
        • 对不起,哥们,但 C# 也接受它,Scheme 和大多数具有 IEEE 浮点的语言也是如此:)
        • 我并不是说 C# 不接受它。这不是普通用户在输入数字时会输入的内容。我宁愿不接受它作为用户的有效输入,但这只是我的意见。
        【解决方案6】:

        如上所述,您可以使用 double.tryParse

        如果你不喜欢这样(出于某种原因),你可以编写自己的扩展方法:

            public static class ExtensionMethods
            {
                public static bool isNumeric (this string str)
                {
                    for (int i = 0; i < str.Length; i++ )
                    {
                        if ((str[i] == '.') || (str[i] == ',')) continue;    //Decide what is valid, decimal point or decimal coma
                        if ((str[i] < '0') || (str[i] > '9')) return false;
                    }
        
                    return true;
                }
            }
        

        用法:

        string mystring = "123456abcd123";
        
        if (mystring.isNumeric()) MessageBox.Show("The input string is a number.");
        else MessageBox.Show("The input string is not a number.");
        

        输入:

        123456abcd123

        123.6

        输出:

        是的

        【讨论】:

          【解决方案7】:

          我认为您可以在 Regex 类中使用正则表达式

          Regex.IsMatch(yourStr, "\d" )

          或类似的东西从我的头顶。

          或者你可以使用 Parse 方法 int.Parse( ... )

          【讨论】:

            【解决方案8】:

            如果您将字符串作为参数接收,则更灵活的方法是使用其他帖子中描述的正则表达式。 如果你从用户那里得到输入,你可以挂上 KeyDown 事件并忽略所有不是数字的键。这样你就可以确定你只有数字。

            【讨论】:

              【解决方案9】:

              这应该可行:

              bool isNum = Integer.TryParse(Str, out Num);
              

              【讨论】:

              • Int.TryParse 将在他的第三个测试用例“123.67”上失败
              猜你喜欢
              • 2014-09-10
              • 1970-01-01
              • 2022-07-28
              • 2021-10-04
              • 2021-11-09
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多