Thursday, August 2, 2018

C# Formatting Leading Zeros Vs Leading Spaces Exhaustive Example

A definitive C# (Sharp) example of formatting leading zeros vs. leading spaces.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
using System;
public class Program
{
 public static void Main()
 {   
  //Leading zeros vs leading spaces  
      DateTime exampleDT = new DateTime(2018, 8, 1, 0, 0, 0, 0);
  
         string exampleHHMMSSusingD2  = string.Format(exampleDT.Hour.ToString("D2")) + ":" + string.Format("{0,3}", exampleDT.Minute.ToString("D2")) + ":" + string.Format("{0:D3}", exampleDT.Second.ToString("D1") +" 2 leading zeros");
         string exampleHHMMSSusing000 = string.Format("{0:00}", exampleDT.Hour.ToString()) + ":" + string.Format("{0:D2}", exampleDT.Minute.ToString()) + ":" + string.Format("{0:11}", exampleDT.Second.ToString()+" no 2 leading zeros");
   
  Console.WriteLine(exampleHHMMSSusingD2);
  Console.WriteLine(exampleHHMMSSusing000);
  Console.WriteLine();
  
  //formatting a string of zeros
  Console.WriteLine(string.Format("{0:00} string", "0000")); 
  Console.WriteLine(string.Format("{0:00} string", Convert.ToInt32("00000"))); 
  Console.WriteLine(string.Format("{0:00} string", Convert.ToInt32(null))); 
     
 }
}

No comments:

Post a Comment