Monday, December 7, 2009

Add leading zeros to a number

Todays post is a very small tip.

I saw the question "How to add leading zeros to a number" on the ASP.NET forums countless times before. And often the answers provide solutions that work, but are overkill as well.

The two cleanest methods I know are String.Format and PadLeft.

   1:  Console.WriteLine("Using .ToString()");
   2:  Console.WriteLine(String.Format("{0:0000}", 16));
   4:  Console.WriteLine("-------------------");
   6:  Console.WriteLine("Using .PadLeft()");
   7:  Console.WriteLine(Convert.ToString(16).PadLeft(4, '0'));

You can see the result here.

//Using .ToString()
//Using .PadLeft()

No comments:

Post a Comment