# How can I format a number into a string with leading zeros?

## Problem

I’m trying to turn an integer into a string. I started with this:

``````Key = i.ToString();
``````

But I realize it’s being sorted in a strange order and so I need to pad it with zeros. How could I do this?

## Solution #1

Rather simple:

``````Key = i.ToString("D2");
``````

The letters D and 2 stand for “decimal number” and “number of digits to print.”

## Solution #2

For various examples of String usage in C#, see String formatting in C#. Format

Actually, here’s a better example of int formatting.

``````String.Format("{0:00000}", 15);          // "00015"
``````

Alternatively, you may use String Interpolation:

``````\$"{15:00000}";                           // "00015"
``````

## Solution #3

If you like a specific width, such as 10 digits, do it this way.

``````Key = i.ToString("0000000000");
``````

Replace the digits with as many as you want.

The result of I = 123 is Key = “0000000123.”

## Solution #4

Since no one has mentioned it yet, you can utilize string interpolation to simplify your code if you’re using C# version 6 or higher (i.e. Visual Studio 2015). As a result, instead of using string, Format(…) is as simple as this:

``````Key = \$"{i:D2}";
``````

## Solution #5

use:

``````i.ToString("D10")
``````

Standard Numeric Format Strings (MSDN) and Int32.ToString (MSDN) (MSDN).

Alternatively, String can be used. PadLeft. As an example,

``````int i = 321;