Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Rather simple:

Key = i.ToString("D2");

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


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


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


For interpolated strings:

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

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

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

is preferable to,

Key = i.ToString("000000");