Possible Duplicate:
C# int ToString format on 2 char int?
Sorry for the simplicity, but this one is eluding me. Pretty much I have a list of 36 records, and if the id is less than 10, I need it to return 01, 02, 03… 09, instead of 1, 2, 3… 9.
Here is the code I have so far and I would have thought this would work. This is C# .NET:
for (int i = 1; i <= 36; i++)
{
if (i.ToString().Length == 1)
{
i.ToString().PadLeft(2,'0');
}
Response.Write("Test: " + i);
}
Any help would be appreciated, thanks in advance!
Your problem is
iis still an integer, it needs to be assigned to a stringHowever, much of this code is superflous, the
ifstatement is not needed. Pad will only ped with zeroes up to the length (2) given. If it’s already 2 or more characters long, it won’t pad anything. All you need is thisFor that matter, the variable is no longer needed.
And if you’ll be padding with zeroes all the time, and not some other character, you could just do this
And you should get into the habit of using
string.FormatAnd to simplify the
string.Formateven further: