【问题标题】:Convert text to integer to compare in C#将文本转换为整数以在 C# 中进行比较
【发布时间】:2018-02-24 17:11:09
【问题描述】:

C# 程序接收到一个标记为:

的字符串
1.2345 V

我需要在 'if' 语句中使用 来比较这个值。 如何将上面的字符串转换为整数? 我尝试使用:

int anInteger;
anInteger = Convert.ToInt32(textBox1.Text);
anInteger = int.Parse(textBox1.Text);

但它会抛出错误System.FormatException: incorrect format

【问题讨论】:

标签: c# textbox type-conversion integer


【解决方案1】:

你可以试试——

 decimal dec=2;
 string str = "3.23456";
 dec = Convert.ToDecimal(str.ToString());
 int a = Convert.ToInt32(dec);

【讨论】:

    【解决方案2】:

    如果你坚持使用 integerdot in 1.2345 应该被忽略,最终结果是 12345):

      // Any digits (including, say, Persian ones) are OK  
      int anInteger = (textBox1.Text
        .Where(c => char.IsDigit(c))
        .Aggregate(0, (s, a) => s * 10 + (int)char.GetNumericValue(a));   
    

    或者

      // Only '0'..'9' digits supported
      int anInteger = (textBox1.Text
        .Where(c => c >= '0' && c <= '9')
        .Aggregate(0, (s, a) => s * 10 + a - '0');   
    

    【讨论】:

      【解决方案3】:

      还请注意,根据您当前的文化设置,您可以获得不同的结果。

      以下代码使用 de-DE 文化设置运行

      System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("de-DE");
      
      string str = "1.23";
      decimal val = decimal.Parse(str);
      val.Dump(); // output 123
      
      string str2 = "1,23";
      decimal val2 = decimal.Parse(str2);
      val2.Dump(); // output 1,23
      

      以下代码使用 en-US 文化设置运行

      System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
      
      string str = "1.23";
      decimal val = decimal.Parse(str);
      val.Dump(); // output 1.23
      
      string str2 = "1,23";
      decimal val2 = decimal.Parse(str2);
      val2.Dump(); // output 123
      

      请使用 LINQPad 运行该代码。

      【讨论】:

        【解决方案4】:

        你必须删除最后的V并使用decimal.Parse/TryParse

        decimal d;
        bool validFormat = decimal.TryParse(textBox1.Text.TrimEnd('V', ' '), out d);
        

        在我使用, 作为十进制和. 作为组分隔符的国家,这会产生12345

        如果您想忽略字符串中不是数字的任何内容:

        int number = int.Parse(new string(textBox1.Text.Where(char.IsDigit).ToArray()));
        

        【讨论】:

        • 在 C#7 中你可以使用out decimal d,以节省一点空间:)
        • 并且您可能必须根据提问者的位置使用不变的文化
        • @YairHalberstadt:嗯,它适用于我,我没有使用 . 作为小数分隔符。结果是12345,有点奇怪
        • 在某些国家它不起作用,程序员会花费数小时试图找出原因。@Tim
        • @YairHalberstadt:修改了我的回答以提及它
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-11-20
        • 1970-01-01
        • 2019-07-24
        • 1970-01-01
        • 2014-04-04
        • 2015-09-27
        • 1970-01-01
        相关资源
        最近更新 更多