Reputation: 597
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't work.
i++.ToString('D2')
Any ideas would be much appreciated
Judy
Upvotes: 2
Views: 1637
Reputation: 128317
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'
Upvotes: 6
Reputation: 70314
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.
Upvotes: 5