Format string to a 3 digit number

Alex picture Alex · Sep 24, 2012 · Viewed 137.5k times · Source

Instead of doing this, I want to make use of string.format() to accomplish the same result:

if (myString.Length < 3)
{
    myString =  "00" + 3;
}

Answer

Reed Copsey picture Reed Copsey · Sep 24, 2012

If you're just formatting a number, you can just provide the proper custom numeric format to make it a 3 digit string directly:

myString = 3.ToString("000");

Or, alternatively, use the standard D format string:

myString = 3.ToString("D3");