C# 在小数点之前计数零

C# 在小数点之前计数零,c#,visual-studio-2012,C#,Visual Studio 2012,我试图数一数小数点前有多少个零 private void textBox1_TextChanged(object sender, EventArgs e) { decimal x = 0; if (Decimal.TryParse(textBox1.Text, out x)) { var y = 1000000; var answer = x

我试图数一数小数点前有多少个零

 private void textBox1_TextChanged(object sender, EventArgs e)
        {
            decimal x = 0;

            if (Decimal.TryParse(textBox1.Text, out x))
            {
                var y = 1000000;
                var answer = x * y;

                displayLabel2.Text = (x.ToString().Replace(".", "").TrimStart(new Char[] { '0' }) + "00").Substring(0, 2);



            }
            else
            {
                displayLabel2.Text = "error";
            }
        }

当我插入(比方说)7.2时,我得到一个显示72的输出,这就是我想要的。现在我需要另一个显示器。最初的7.2乘以1000000。所以它的引用值是7200000.00。现在我需要知道如何计算小数点前的5个零,并显示5。那如果我要做的话。我的报价是720000.00。我需要显示4,对于4个零。等等然后,我需要将该数字输出到displayLabel5.Text

快速脏代码,所以要小心,但这是最快的方法

// Input assuming you've sanitised it
string myInputString = "720000.00";

// Remove the decimals
myInputString = myInputString.Substring(0, myInputString.IndexOf("."));

// The count
int count = 0;

// Loop through and count occurrences
foreach (char c in myInputString) 
{
    if (c == "0")
    {
        count++;
    }
}
计数现在是4

向您保证这比正则表达式更快;-)


编辑:很抱歉进行了多次编辑,这是漫长的一天。需要咖啡。

使用正则表达式查找句点之前的所有零,然后获取匹配的字符串长度

Regex regex = new Regex(@"(0+)\.?");
string value1 = "7,200,000.00";
value1 = value1.Replace(",",""); //get rid of the commas
Match match = regex.Match(value1);
if (match.Success)
{
    Console.WriteLine(match.Value.Length);
}
像往常一样测试代码,因为我刚才在这个小文本框中编写了代码,而不是在实际的VisualStudio中,在那里我可以自己编译和测试代码。但这至少应该说明方法论

编辑:
稍微调整正则表达式,以考虑数字根本不显示小数点的可能性。

这里有一行
Linq
您可以尝试在小数点之前数零。您可以先按小数进行拆分(),然后执行
Where().Count()
以获得零的数量

using System;
using System.Linq;

public class Program
{
    public static void Main()
    {
        string myString = (720000.00).ToString();
        Console.WriteLine(myString.Split('.')[0].Where(d => d == '0').Count());
    }
}
结果:

4