簡體   English   中英

計算小數點之前的零

[英]Count Zeroes before the Decimal Point

我試圖計算十進制前有多少個零。

 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。因此,其報價為7,200,000.00。 現在,我需要一些如何計算小數點前的5個零並顯示5。 然后,如果我要.72。 我的報價為720,000.00。 我需要顯示4,代表4個零。 等等。 然后我需要將該數字輸出到displayLabel5.Text

快速而骯臟的代碼要當心,但是AFAIK這是最快的方法。

// 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);
}

一如既往地測試代碼,因為我剛才在這里的小文本框中編寫了該代碼,而不是在我自己可以進行編譯和測試的實際Visual Studio中編寫的。 但這至少應該說明方法。

編輯:略微調整正則表達式,以解決該數字根本不會顯示小數點的可能性。

這是一行Linq您可以嘗試在小數點之前計算零。 您可以先用小數點Split() ,然后執行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

演示版

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM