Search code examples
c#stringstring-formatting

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?


Solution

  • Rather simple:

    Key = i.ToString("D2");
    

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