C# – How to Convert int to string with padding zeros ?

This simple tip in C# shows you how to convert int to string by padding it with zeros. Assume that you have an integer value in C# that you will need to convert to string but with zeros prefixed with.

For example , You have an integer value containing 23 and you would like to display it as 0023.

How to Convert int to string with padding zeros in C#?

There are couple of options to get it work

  1. Use ToString with the Format Specifier D4
  2. Use String Interpolation in C# 6 and higher version.

Use ToString with the Format Specifier D4 in C#

Here’s a code snippet demonstrating how to use Format Specifier D4

public class Hello {
    public static void Main() {
        int input= 23;
        string result = input.ToString("D4");
        System.Console.WriteLine(result);
    }
}

Output

Use String Interpolation in C#

Here’s a code snippet demonstrating how to use string interpolation in C#.

 public class Hello {
    public static void Main() {
        int input= 23;
        string result = $"{input:0000}";
        System.Console.WriteLine(result);
    }
   
}

Output

Share:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...