Advertisement
Advertisement

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

### Question

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?

2015/03/27
1
258
3/27/2015 9:51:09 AM

### Accepted Answer

Rather simple:

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

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

2015/03/27
355
3/27/2015 9:52:33 AM

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"`.

2018/02/28

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}";
``````
2016/04/10

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).

2015/05/08

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

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

is preferable to,

``````Key = i.ToString("000000");
``````
2013/04/16

Try:

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

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

2011/03/24

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]