How to Add Leading Zeros to an Integer in C#.NET? [With Examples]

In this tutorial, I have explained, how to add leading zeros to an integer in C#.Net. There are various methods to add leading zeros to integer in c#.

1. Padding Integer with Leading Zeros using ToString()

In C#, the ToString method of a number can accept a format string that provides formatting information. You can use “Dn” as a format, where ‘n’ is the total length you want your number to be. If the integer is shorter than ‘n’, it will be padded with leading zeros.

Example:

using System;

public class Program
{
    public static void Main()
    {
        int num = 123;
        string formatted = num.ToString("D5");

        Console.WriteLine(formatted);  // Prints: 00123
    }
}

In this example, ToString("D5") is used to format num to be 5 digits long, padding with leading zeros as necessary. You can see the output:

add leading zeros to integer in c#
add leading zeros to integer in c#

2. using String.Format() method

The String.Format() method can be used to apply a similar kind of formatting to the integer. Below is an example to add leading zeros to an integer in c#.net.

Example:

using System;

public class Program
{
    public static void Main()
    {
        int num = 123;
        string formatted = String.Format("{0:D5}", num);

        Console.WriteLine(formatted);  // Prints: 00123
    }
}

Here, String.Format("{0:D5}", num) is used to format num as a 5 digit decimal, again padding with leading zeros where needed.

3. Adding Leading Zeros using Interpolated Strings

Interpolated strings provide a more readable way to format strings, including padding integers with leading zeros. They start with a $ character and allow expressions between {} brackets directly in the string.

Example:

using System;

public class Program
{
    public static void Main()
    {
        int num = 123;
        string formatted = $"{num:D5}";

        Console.WriteLine(formatted);  // Prints: 00123
    }
}

In this example, the interpolated string $"{num:D5}" is used to format num as a 5 digit decimal, adding leading zeros as required.

In this tutorial, we learned how to add leading zeros to an integer in C#.NET. We discovered that we can use the ToString method, the String.Format method, and interpolated strings for this purpose. Now you can apply these methods to format numbers in your own C#.NET programs.

You may also like: