69

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?

1

5 Answers 5

128

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

n.ToString("D2")
1
  • dotnet 6 allows $"{n:D2}" syntax. Dec 12, 2023 at 10:59
34
string.Format("{0:00}", yourInt);

yourInt.ToString("00");

Both produce 01, 02, etc...

12
string.Format("{0:00}",1); //Prints 01
string.Format("{0:00}",2); //Prints 02
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.