计算小数点前的零 [英] Count Zeroes before the Decimal Point
问题描述
我正在尝试计算小数点前有多少个零.
I am trying to count how many zeroes are a before a decimal.
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.然后,如果我要做 0.72.我的 Quotent 是 720,000.00.我需要为 4 个零显示 4.等等.然后我需要将该数字输出到 displayLabel5.Text
When I plug in (lets say) 7.2 I get an output that displays 72, which is what I want. Now I need another display. That initial 7.2 is being multiplied by 1000000. So the quotent of that would be 7,200,000.00. Now I need to some how count the 5 zeroes before the decimal point and display 5 for that. Then if I were to do .72. My Quotent would be 720,000.00. And I would need to display 4, for the 4 zeroes. And so on. Then I need to output that number to displayLabel5.Text
推荐答案
这是一行 Linq
您可以尝试计算小数点前的零.您可以先Split()
按小数,然后执行Where().Count()
以获得零的数量.
Here's a one line Linq
you could try to count zeroes before the decimal. You can Split()
first by the decimal then perform a Where().Count()
to get the number of zeros.
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
这篇关于计算小数点前的零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!