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

I have a number that I need to convert to a string. First I used 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?

This question is related to c# string string-formatting

The answer is


Rather simple:

Key = i.ToString("D2");

D stands for "decimal number", 2 for the number of digits to print.


For interpolated strings:

$"Int value: {someInt:D4} or {someInt:0000}. Float: {someFloat: 00.00}"

See String formatting in C# for some example uses of String.Format

Actually a better example of formatting int

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

or use String Interpolation:

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

If you like to keep it fixed width, for example 10 digits, do it like this

Key = i.ToString("0000000000");

Replace with as many digits as you like.

i = 123 will then result in Key = "0000000123".


int num=1;
string number=num.ToString().PadLeft(4, '0')

Output="00001"

EDIT: Changed to match the PadLeft amount


Usually String.Format("format", object) is preferable to object.ToString("format"). Therefore,

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

is preferable to,

Key = i.ToString("000000");

Try:

Key = i.ToString("000000");

Personally, though, I'd see if you can't sort on the integer directly, rather than the string representation.


Here I want my no to limit in 4 digit like if it is 1 it should show as 0001,if it 11 it should show as 0011..Below are the code.

        reciptno=1;//Pass only integer.

        string formatted = string.Format("{0:0000}", reciptno);

        TxtRecNo.Text = formatted;//Output=0001..

I implemented this code to generate Money receipt no.


Since nobody has yet mentioned this, if you are using C# version 6 or above (i.e. Visual Studio 2015) then you can use string interpolation to simplify your code. So instead of using string.Format(...), you can just do this:

Key = $"{i:D2}";

use:

i.ToString("D10")

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

Or use String.PadLeft. For example,

int i = 321;
Key = i.ToString().PadLeft(10, '0');

Would result in 0000000321. Though String.PadLeft would not work for negative numbers.

See String.PadLeft (MSDN).