问题
I need to count an amount of zeroes. So far this code works:
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (uFCheckBox.Checked == true)
{
nFCheckBox.Checked = false;
pFCheckBox.Checked = false;
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);
string myString = answer.ToString();
// displayLabel5.Text = myString.Split('.')[0].Where(d => d == '0').Count().ToString();
displayLabel5.Text = myString.Split('.')[0].Where(d => d == '0').Count().ToString();
}
It counts zero perfectly when I input numbers like 72, 47, 83, etc. But once I input numbers that end with a zero, it counts that zero. I need something that counts all zeroes after the first 2 digits. So 50 x 1,000,000 will be 50,000,000. but I dont need to count the first 2 digits, so I need it to output 6 in this scenario. More example:
1.0 x 1,000,000 = 1,000,000 - I only need to output 5 zeroes
0.10 x 1,000,000 = 100,000 - I only need to output 4 zeroes.
But I also need to maintain that if I input other numbers that dont "end" in zeroes it still counts properly. Examples:
72 x 1,000,000 = 72,000,000 - Needs to output 6
7.2 x 1,000,000 = 7,200,000 - Needs to output 5
.72 x 1,000,000 = 720,000 - Needs to output 4
Update: I am now getting proper outputs when I use
decimal n = str.Split('.')[0].Substring(2, str.Length - 2).Count( s => s == '0');
but now I get an error: "Index and length must refer to a location within the string. Parameter name: length"
回答1:
If I understand this correctly you just want it to output the number of zeros. To do this you would do the following:
var y = 1000000;
var answer = x * y;
string numString = answer.ToString();
char[] charArray = numString.ToCharArray();
int count = 0;
for(int i = 2; i < charArray.Length; i++)
{
if(charArray[i] == '0')
{
count++;
}
}
string output = count.ToString();
Using this, output will be the string count of zeros after the first 2 digits.
回答2:
var y = 1000000;
var answer = x * y;
var str= answer.ToString();
var n = str.Substring(2, str.Length - 2).Count(s => s == '0');
来源:https://stackoverflow.com/questions/31167017/how-to-count-zeroes-with-specific-parameters