可能重複:
Number formatting: how to convert 1 to "01", 2 to "02", etc.?將int(數字)轉換爲前導零的字符串? (4位)
如何使用下面的方案我轉換int
到string
?
1
轉換爲0001
123
轉換爲0123
當然,字符串的長度是動態的。對於此示例,它是:
int length = 4;
我該如何轉換它?
可能重複:
Number formatting: how to convert 1 to "01", 2 to "02", etc.?將int(數字)轉換爲前導零的字符串? (4位)
如何使用下面的方案我轉換int
到string
?
1
轉換爲0001
123
轉換爲0123
當然,字符串的長度是動態的。對於此示例,它是:
int length = 4;
我該如何轉換它?
使用String.PadLeft這樣的:
var result = input.ToString().PadLeft(length, '0');
使用toString()方法 - standard和custom數字格式字符串。看看MSDN文章How to: Pad a Number with Leading Zeros。
string text = no.ToString("0000");
val.ToString("".PadLeft(length, '0'))
使用爲您提供的格式選項,使用Decimal格式字符串。與直接字符串操作相比,它更加靈活並且幾乎不需要維護。
要使用至少4位獲得字符串表示:
int length = 4;
int number = 50;
string asString = number.ToString("D" + length); //"0050"
http://stackoverflow.com/questions/4432734/c-sharp-pad-left-to-string,HTTP://計算器.com/questions/5972949/number-formatting,http://stackoverflow.com/questions/4325267/c-sharp-convert-int-to-string-with-padding-zeros – 2011-12-11 07:59:04