【问题标题】:TryParse for numbers in C#?TryParse 用于 C# 中的数字?
【发布时间】:2013-11-07 07:19:58
【问题描述】:

所以我想使用 TryParse 方法,但到目前为止我只能使用整数或双精度值。但是,我想检查该值是否是一个数字,如果不是(例如,如果它是一个字符串)得到一个假值。像 IsDigit() 这样的东西是 Java。

static void Main()
    {
        int number;
        Console.Write("Enter a number: ");
        bool result = Int32.TryParse(Console.ReadLine(), out number); 
        if (result)
        {
            Console.WriteLine("The input number is an integer.");
        }

        else
        {
            Console.WriteLine("The input number is not an integer.");
        }
    }

所以我想这样做,但不是检查整数值,而是检查数值。所以如果有人能告诉我我可以使用什么方法,我会很高兴。 提前致谢!

【问题讨论】:

  • “数值”是什么意思,为什么对整数或双精度数的 TryParse 不满意?
  • 我还想知道 Boyan Kushlev 认为“数值”和双精度之间的区别是什么。什么字符串可以表示一个数字,但不能解析为双精度数?
  • 任何非数字都会返回false,这里有什么问题??
  • @Tobberoth 1e123456789 是一个数字,但不能解析为双精度数。
  • @DavidArno 我同意,如果您不需要将数字作为数字变量,那么正则表达式似乎是更好的选择。

标签: c# tryparse


【解决方案1】:

使用double:

double number;
bool result = double.TryParse(Console.ReadLine(), out number); 

这将解析任何个实数。

【讨论】:

  • 不,不会。有很多实数超出了它的解析能力。
  • 试试double.TryParse("1e123456789", out number)。它将返回 false。
  • 是的,我明白你的意思,答案是正确的,因为它符合他对数值的定义。
  • @Ofiris :我怎样才能让它在解析 1.2.3 时返回 false。
【解决方案2】:

十进制或双精度类型的 TryParse 是内置方法的限制。如果你想要更多,你必须自己解析字符串。使用正则表达式可以很容易地完成,例如

^-?[0-9]+\.?[0-9]*([Ee][+-]?[0-9]+)?$

【讨论】:

  • 假设输入是e3,你会将它转换成哪个double,如何转换?您如何将输入转换为您可以使用的变量? (任何输入)
  • @Ofiris "e3" 与正则表达式不匹配,因为[0-9]+ 部分至少需要一位数字。
  • var regex = new Regex(@"-?[0-9]+\.?[0-9]*([Ee][+-]?[0-9]+)?"); var m = regex.Match("5.5.5"); // .Success == True
  • @Ofiris 很好发现。现在更新为只匹配整个字符串,而不仅仅是它的一部分。
  • 好的,那么+1,我认为这次最好保持简单,但你的答案也是正确的。
【解决方案3】:
bool result = double.TryParse(mystring, out num);

double.TryParse 也适用于整数。

【讨论】:

    【解决方案4】:

    对于单个字符,有Char.IsDigit()。在这种情况下,您可能想查看Console.ReadKey() 而不是阅读整行。顺便说一句,Char.IsDigit() 也匹配数字 from other cultures

    对于多个字符,您需要考虑要接受什么。小数、指数、负数还是只是多个数字字符?

    【讨论】:

      【解决方案5】:

      你可以试试正则表达式

      var regex = new Regex(@"^-*[0-9\.]+$");
      var m = regex.Match(text);
      if (m.Sucess)
          {
              Console.WriteLine("The input number is an integer.");
          }
      
          else
          {
              Console.WriteLine("The input number is not an integer.");
          }
      

      您还可以通过在正则表达式中包含分隔符来允许分隔符。

      【讨论】:

        【解决方案6】:
        static bool enteredNumber()
        {
            int intValue;
            double doubleValue;
            Console.Write("Enter a number: ");
            string input = Console.ReadLine();
            return Int32.TryParse(input, out intValue) ? true : double.TryParse(input, out doubleValue);
        }
        

        【讨论】:

        • Int32.TryParse(input, out intValue) 不需要,因为它被后者覆盖了。
        猜你喜欢
        • 2013-12-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多