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!
To add leading zeros to a number, you need to format the output. Let's say we need to add 4 leading zeros to the following number with 3 digits. int val = 290; For adding 4 leading zeros above, we will use %07d i.e. 4+3 = 7.
Use the String() object to convert the number to a string. Call the padStart() method to add zeros to the start of the string. The padStart method will return a new, padded with leading zeros string.
String(num). padStart(5, "0"); Here, num is the number whose leading zeroes need to be preserved. 5 is the number's target length, and the "0" needs to be padded at the front using the padStart() method.
You don't need IF, use ToString
int i = 5;
i.ToString("00"); //returns 05
Your problem is i
is still an integer, it needs to be assigned to a string
for (int i = 1; i <= 36; i++)
{
var iString = i.ToString();
if(iString.Length == 1)
{
iString = iString.PadLeft(2,'0'); //RIGHT HERE!!!
}
Response.Write("Test: " + iString);
}
However, much of this code is superflous, the if
statement 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 this
for (int i = 1; i <= 36; i++)
{
var iString = i.ToString().PadLeft(2,'0');
Response.Write("Test: " + iString);
}
For that matter, the variable is no longer needed.
for (int i = 1; i <= 36; i++)
{
Response.Write("Test: " + i.ToString().PadLeft(2,'0'));
}
And if you'll be padding with zeroes all the time, and not some other character, you could just do this
for (int i = 1; i <= 36; i++)
{
Response.Write("Test: " + i.ToString("00"));
}
And you should get into the habit of using string.Format
for (int i = 1; i <= 36; i++)
{
Response.Write(string.Format("Test: {0}", i.ToString("00")));
}
And to simplify the string.Format
even further:
for (int i = 1; i <= 36; i++)
{
Response.Write(string.Format("Test: {0:00}", i));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With