C# | Padding an integer number with leading zeros

In this tutorial, we will learn how to pad an integer number with leading zero in C#? By IncludeHelp Last updated : April 09, 2023

Padding an integer number with leading zeros

To pad an integer number with leading zero, 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 zeros,

String.Format("{0:000000}", number)

C# code for padding an integer number with leading zeros

using System;

namespace ConsoleApplication1 {
  class Program {
    static void Main(string[] args) {
      Console.WriteLine("Demo for pad zeros before an integer number:");

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

      Console.WriteLine();
    }
  }
}

Output

Demo for pad zeros before an integer number:
000256
-000256

Explanation

In the above program, we are printing 256 and -256 numbers in 6 digits, as we know that 256 has 3 digits and we are padding (left/leading) them with zeros.




All C#.Net Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.