C# Padding an integer number with leading and trailing spaces/zeros

C# String.Format() technique example: Here, we will figure out how to pad an integer number with driving and trailing spaces/zeroes in C#?

To pad an integer number with driving and trailing spaces/zeroes, we can utilize String.Format() strategy which is library technique for String class in C#.

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Demo for left or right alignment of an integer number:");

            Console.WriteLine(String.Format("{0,6}"         , 256));
            Console.WriteLine(String.Format("{0,-6}"        , 256));
            Console.WriteLine(String.Format("{0,6:00000}"   , 256));
            Console.WriteLine(String.Format("{0,-6:00000}"  , 256));

            Console.WriteLine();  
        }
    }
}

Output:

Demo for left or right alignment of an integer number:
   256
256
 00256
00256

In the above program, 6 is utilized for the right arrangement, here space is padded at the left side. Furthermore, on account of – 6, it is turn around. Furthermore, we additionally padded zeros.

Leave a Comment

error: Alert: Content is protected!!