Coder Perfect

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


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?

Asked by Mandy Weston

Solution #1

Rather simple:

Key = i.ToString("D2");

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

Answered by Mario

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"

Answered by Paul

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

Answered by Øyvind Bråthen

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}";

Answered by DavidG

Solution #5



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

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

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

0000000321 would be the result. Negative integers, however, would not work with String.PadLeft.

See String.PadLeft (MSDN).

Answered by firefox1986

Post is based on