Friday, April 6, 2012

How to pad number with leading zero with C#

Author : Prakash Pradeep Gopu
Recently I was working with a project where I was in need to format a number in such a way which can apply leading zero for particular format. That means I need to pad number in 6 digit format. So following is a table in which format I need my leading zero format.
1-> 000001
20->000020
300->000300
4000->004000
50000->05000
600000à600000

So in the above example you can see that 1 will become 000001 and 20 will become 000200 format so on. So to display an integer value in decimal format I have applied interger.Tostring(String) method where I have passed “Dn” as the value of the format parameter, where n represents the minimum length of the string. So if we pass 6 it will have padding up to 6 digits.
For better understanding create a simple console application and see how its works. Following is a code for that.


class LeadingZeros
    {
        static void Main(string[] args)
        {
            int a = 1;
            int b = 20;
            int c = 300;
            int d = 4000;
            int e = 50000;
            int f = 600000;

            Console.WriteLine(string.Format("{0} Turns to {1}", a, a.ToString("D6")));
            Console.WriteLine(string.Format("{0} Turns to {1}", b, b.ToString("D6")));
            Console.WriteLine(string.Format("{0} Turns to {1}", c, c.ToString("D6")));
            Console.WriteLine(string.Format("{0} Turns to {1}", d, d.ToString("D6")));
            Console.WriteLine(string.Format("{0} Turns to {1}", e, e.ToString("D6")));
            Console.WriteLine(string.Format("{0} Turns to {1}", f, f.ToString("D6")));
            Console.ReadLine();
        }
}

Output :

No comments:

Post a Comment