String format number leading zero
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | class Program { static void Main(string[] args) { //this line create a int variable. int number = 12345; Console.WriteLine("formatted string.............."); int length = number.ToString().Length + 1; string dValue = "D" + length.ToString(); Console.WriteLine("Number: " + number); //format string using ToString method Console.WriteLine("String format number leading zero: " + number.ToString("D6")); //format string using string.format method. Console.WriteLine("String format number leading zero: " + string.Format("{0:D6}", number)); //dynamically determine number length and format string. Console.WriteLine("\nAnother dynamic option: " + number.ToString(dValue)); //another technique to format string using padleft method. Console.WriteLine("Another technique: " + number.ToString().PadLeft(length, '0')); Console.ReadLine(); } } |
Output:
1 2 3 4 5 6 7 8 9 | formatted string.............. Number: 12345 String format number leading zero: 012345 String format number leading zero: 012345 Another dynamic option: 012345 Another technique: 012345 |