[c#] Convert int (number) to string with leading zeros? (4 digits)

Possible Duplicate:
Number formatting: how to convert 1 to "01", 2 to "02", etc.?

How can I convert int to string using the following scheme?

  • 1 converts to 0001
  • 123 converts to 0123

Of course, the length of the string is dynamic. For this sample, it is:

int length = 4;

How can I convert like it?

This question is related to c# c#-4.0

The answer is


Use the ToString() method - standard and custom numeric format strings. Have a look at the MSDN article How to: Pad a Number with Leading Zeros.

string text = no.ToString("0000");

val.ToString("".PadLeft(length, '0'))


Use the formatting options available to you, use the Decimal format string. It is far more flexible and requires little to no maintenance compared to direct string manipulation.

To get the string representation using at least 4 digits:

int length = 4;
int number = 50;
string asString = number.ToString("D" + length); //"0050"