我有一個4字節的值,我將其轉換爲Int32,然後將其顯示在文本框中。那裏沒有問題。當我嘗試用0填充字符串時,問題就出現了。當我顯示小數時,它應該總是包含8個字符,所以如果小於這個數字,我想用0填充它。C#For循環不能正確迭代
string parmDecString = BitConverter.ToInt32(testNum, 0).ToString();
Console.WriteLine("length: {0} - {1}", parmDecString.Length, (8 - parmDecString.Length));
for (int l=0; l < (8-parmDecString.Length); l++)
{
parmDecString = "0" + parmDecString;
}
textBox74.Text = parmDecString;
下面是在文本框中輸出我得到基於不同的「parmDecString的價值觀:在每個循環
parmDecString = "123"
Console: length: 3 - 5
textbox: 00<=== only 3 times in the 'for' loop, expected 5x
parmDecString = "12345"
Console: length: 5 - 3
textbox: 0<=== only 2 times in the 'for' loop, expected 3x
parmDecString = "12345678"
Console: length: 8 - 0
textbox: 12345678 <=== as expected
'parmDecString.Length'正在改變。 – SLaks
我同意SLaks –
或者,只需使用PadLeft https://msdn.microsoft.com/en-us/library/92h5dc07(v=vs.110).aspx – hatchet