You can pad an integer with leading zeros by using the “D” string format specifier. You can pad integer, floating-point and negative numbers with leading zeros by using a “D” format string.
The following example formats all four integral types values including negative value to the string of length 8.
byte byteValue = 254; short shortValue = 10342; int intValue = 10; int negativeValue = -254; Console.WriteLine(byteValue.ToString("D6")); Console.WriteLine(shortValue.ToString("D6")); Console.WriteLine(intValue.ToString("D6")); Console.WriteLine(negativeValue.ToString("D6")); Console.WriteLine();
The result of the above code will be:
000254
010342
000010
-000254
The “D” format specifier converts a number to a string of decimal digits. This format is supported only for integral types.
To pad an integer with a specific number of leading zeros
The following example adds the three leading zeros into the integral types values:
byte byteValue = 254; short shortValue = 10342; Console.WriteLine(byteValue.ToString("D").Length + 3); Console.WriteLine(shortValue.ToString("D").Length + 3)); Console.WriteLine();
The result of the above code will be:
000254
00010342