开发者

How can I format an integer variable so it becomes a leading zero string

Need some help with C#.

I have a variable i that has numbers from 1 to 20. I would like to convert this variable so it displays 01,02 etc as a string and then have it increment. I tried to do this with the following but it didn'开发者_JS百科t work.

i++.ToString('D2')

Any ideas would be much appreciated

Judy


Try this:

i++.ToString("00")

Update: Actually, the solution you tried should also work just fine. You just need to enclose "D2" in double quotes rather than single quotes (single quotes are used to denote char values in C# rather than strings):

i++.ToString("D2") // note: "D2", not 'D2'


try this:

string.Format("{0:00}", i++);

Also, be sure to read SteveX on string formatting in C#. That site really nails it, giving you all the information you could ever want on string formatting in .NET.

It seems you can also pass the format string to the ToString method:

i++.ToString("00");

This is slightly less generic as you can't format multiple variables to one string, but if you only need to format that one integer, it will do the trick.


i++.ToString().PadLeft(2, "0");


Try also this:

i++.ToString().PadLeft(2, '0');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜