john wagner
john wagner

Reputation: 811

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?

Upvotes: 70

Views: 130197

Answers (5)

Sourodeep Chatterjee
Sourodeep Chatterjee

Reputation: 197

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

Upvotes: 8

as an example

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

just simple and Worked.

Upvotes: 0

Kelsey
Kelsey

Reputation: 47736

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

yourInt.ToString("00");

Both produce 01, 02, etc...

Upvotes: 34

porges
porges

Reputation: 30580

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

n.ToString("D2")

Upvotes: 129

Tushar
Tushar

Reputation: 1262

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

Upvotes: 12

Related Questions