98

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?

Community
  • 1
  • 1
Ehsan
  • 3,431
  • 8
  • 50
  • 70
  • http://stackoverflow.com/questions/4432734/c-sharp-pad-left-to-string , http://stackoverflow.com/questions/5972949/number-formatting , http://stackoverflow.com/questions/4325267/c-sharp-convert-int-to-string-with-padding-zeros –  Dec 11 '11 at 07:59

4 Answers4

149

Use String.PadLeft like this:

var result = input.ToString().PadLeft(length, '0');
Jens
  • 25,229
  • 9
  • 75
  • 117
  • c=1 a="%03d"%(c) this works perfectly – shiny Jan 20 '14 at 07:36
  • 5
    This not a good solution. Using this, you have to figure out the current length of the numbers and add the right amount of zeroes. E.g. 2 zeroes for 12 and 1 zero for 123. Using .ToString("Dx") is much better. – arrkaye Jun 22 '17 at 13:07
  • 5
    That is not true. PadLeft takes the total number of letters as an argument, not the one to add. So "1".PadLeft(4, '0') is "0001". – Jens Jun 25 '17 at 18:14
  • 4
    Not a good pattern, you allocate and copy the string twice and just using the most naive solution you know. `ToString` has an argument just for this purpose, use that. – Jakub Míšek Aug 09 '18 at 11:50
  • 4
    Jeffs solution below would be better – Markus Knappen Johansson Feb 25 '20 at 11:18
112

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"
Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272
94

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");
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
KV Prajapati
  • 93,659
  • 19
  • 148
  • 186
4

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

MagnatLU
  • 5,967
  • 1
  • 22
  • 17