This article illustrates the different techniques to convert an int to a string that is padded with leading zeros to a specified length.

1. Using String.PadLeft() method

The standard way to convert an int to a string with leading zeros in C# is using the String.PadLeft() method. It returns a new string of a specified length, with the string left padded with spaces or the specified character. Here’s the working example, which uses the PadLeft() method to create a new 8-digit string from the given number padded with all zeros.

Download  Run Code

2. Using Int32.ToString() method

Alternatively, you can use the Int32.ToString() method to convert a numeric value to its equivalent string representation. It is overloaded to accept a standard or custom numeric format string. The following example formats an Int32 value using the “D” format specifier with a precision specifier of 8:

Download  Run Code

 
The following solution uses the “0” custom format specifier as a zero-placeholder symbol.

Download  Run Code

3. Using String.Format() method

Another option is to use the String.Format() method to pad a string with leading or trailing characters to a specified length. The following example formats an Int32 value using the “D” format specifier with a precision specifier of 8:

Download  Run Code

 
You can also use the “0” custom format specifier, as shown below:

Download  Run Code

4. Using String Interpolation

Starting with C# 6.0, you can format your string using the String Interpolation ‘$’. It provides a more concise syntax to format strings, which is easier to read than traditional string formatting methods. With String Interpolation, the above code can be shortened to:

Download  Run Code

 
Or, use the “0” custom format specifier:

Download  Run Code

That’s all about converting an int to a string with leading zeros in C#.