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

Mandy Weston picture Mandy Weston · Mar 24, 2011 · Viewed 320.6k times · Source

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?

Answer

Mario picture Mario · Mar 24, 2011

Rather simple:

Key = i.ToString("D2");

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