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

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?


Solution 1:

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

n.ToString("D2")

Solution 2:

string.Format("{0:00}", yourInt);

yourInt.ToString("00");

Both produce 01, 02, etc...

Solution 3:

string.Format("{0:00}",1); //Prints 01
string.Format("{0:00}",2); //Prints 02

Solution 4:

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}");

Solution 5:

as an example

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

just simple and Worked.