Home »
C# Tutorial
C# | Padding an integer number with leading and trailing spaces/zeros
In this tutorial, we will learn how to pad an integer number with leading and trailing spaces/zeros in C#?
By IncludeHelp Last updated : April 09, 2023
Padding an integer number with leading and trailing spaces/zeros
To pad an integer number with leading and trailing spaces/zeros, we use String.Format() method which is library method of String class in C#. It converts the given value based on the specified format.
Consider the below statement for padding with leading and trailing spaces/zeros,
String.Format("{0,6:00000}", number)
// Here, 6 is the number of digits
C# code for padding an integer number with leading and trailing spaces/zeros
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
Explanation
In the above program, 6 is used for right alignment, here space is padded at the left side. And in the case of -6, it is reverse. And we also padded zeros.