18

How do I apply a mask to a string aiming to format the output text in the following fashion (at most 2 leading zeros):

int a = 1, b = 10, c = 100;
string aF = LeadingZeroFormat(a), bF = LeadingZeroFormat(b), cF = LeadingZeroFormat(c);
Console.Writeline("{0}, {1}, {2}", aF, bF, cF); // "001, 010, 100" 

What is the most elegant solution?

Thanks in advance.

João Paulo Navarro
  • 544
  • 1
  • 7
  • 16

3 Answers3

48

You can use Int32.ToString("000") to format an integer in this manner. For details, see Custom Numeric Format Strings and Int32.ToString:

string one = a.ToString("000"); // 001
string two = b.ToString("000"); // 010
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
17

As well as Reed's suggestion, you can do it directly in your compound format string:

int a = 1, b = 10, c = 100;
Console.WriteLine("{0:000}, {1:000}, {2:000}", a, b, c); // "001, 010, 100"
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
3

To display the integer as a decimal value, call its ToString(String) method, and pass the string "Dn" as the value of the format parameter, where n represents the minimum length of the string.

int i = 10;
Console.WriteLine(i.ToString("D3"));

Also check How to: Pad a Number with Leading Zeros

Habib
  • 219,104
  • 29
  • 407
  • 436