【问题标题】:Parsing to double and ignoring letters and whitespace解析为双精度并忽略字母和空格
【发布时间】:2015-10-20 19:00:39
【问题描述】:

我在这里定义价格:

lblPrisGrill.Text = "20,00 ,-"; // Grill
lblPrisWiener.Text = "25,00 ,-"; // Wiener
lblPrisBacon.Text = "35,00 ,-"; // Bacon
lblPrisOst.Text = "30,00 ,-"; // Oste

我将价格从字符串解析为双倍(数字):

if (rbGrill.Checked == true)
    PrisMeny = double.Parse(lblPrisGrill.Text);

else if (rbWiener.Checked == true)
    PrisMeny = double.Parse(lblPrisWiener.Text);

else if (rbBacon.Checked == true)
    PrisMeny = double.Parse(lblPrisBacon.Text);

else if (rbOst.Checked == true)
    PrisMeny = double.Parse(lblPrisOst.Text);

我想知道我如何只能得到号码"##,##" 而忽略" ,-"。

我知道存在解释这一点的资源,但我想知道如果我有多个任务会怎样,并看看它会如何完成。

【问题讨论】:

    标签: c# webforms


    【解决方案1】:

    您可以简单地使用String.Replace 删除该部分:

    string s = "20,00 ,-";
    
    double d = double.Parse(s.Replace(",-", ""));
    Console.WriteLine(d); // 20.0
    

    【讨论】:

    • 为什么不包含不需要调用 trim 的空间
    • @Sorceri 我想去掉任何空格,因为这似乎是用户输入,但事实证明,double.Parse 可以很好地处理数字周围的空格。 (也不包括那里的空间,以确保如果以后忘记空间,替换不会失败)
    【解决方案2】:

    您可以使用正则表达式来查找匹配的表达式。我创建了this dotnet fiddle 来演示您的场景。您可以检查小提琴的输出。附上代码供参考。

    using System;
    using System.Text.RegularExpressions;
    
    public class Program
    {
        public static void Main()
        {
            var text = "200,001 ,-"; 
    
            var regex = new Regex(@"\d\d*,\d\d*");
            foreach(var match in regex.Matches(text))
            {
                Console.WriteLine(match.ToString());
            }
    
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-21
      • 2010-11-27
      • 1970-01-01
      • 1970-01-01
      • 2022-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多