64

I have numbers like 1, 2, and 3, and I would like to make them into strings, "01", "02" and "03". How can I do this?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
john wagner
  • 751
  • 1
  • 7
  • 8

5 Answers5

123

Here is the MSDN article on formatting numbers. To pad to 2 digits, you can use:

n.ToString("D2")
porges
  • 30,133
  • 4
  • 83
  • 114
34
string.Format("{0:00}", yourInt);

yourInt.ToString("00");

Both produce 01, 02, etc...

Kelsey
  • 47,246
  • 16
  • 124
  • 162
12
string.Format("{0:00}",1); //Prints 01
string.Format("{0:00}",2); //Prints 02
Tushar
  • 1,242
  • 1
  • 8
  • 19
8

With new C# (I mean version 6.0), you can achieve the same thing by just using String Interpolation

int n = 1;
Console.WriteLine($"{n:D2}");
0

as an example

int num=1;
string number=num.ToString().PadLeft(2, '0')

just simple and Worked.