C# FAQ 6 - How Do I Display Numbers In Different Formats

C# enables you to display numbers, date and time in various formats as per your requirements. In order to work with this feature, you need to make use of specifiers inside braces.
Let us now examine how to display numbers in various formats. Copy and save the code given below with the file name Numberdemo.cs,
  1. using System;  
  2. class Numberdemo   
  3. {  
  4.     public static void Main()   
  5.   {  
  6.         int x = 23456;  
  7.         Console.WriteLine("{0:C}", x);  
  8.         Console.WriteLine("{0:D}", x);  
  9.         Console.WriteLine("{0:E}", x);  
  10.         Console.WriteLine("{0:F}", x);  
  11.         Console.WriteLine("{0:G}", x);  
  12.         Console.WriteLine("{0:N}", x);  
  13.         Console.WriteLine("{0:X}", x);  
  14.         Console.WriteLine("{0:x}", x);  
  15.     }  
  16. }  
The next step is to compile the code. If there are any errors, the C# compiler will display them, otherwise you can execute and run the program. You will view an output as shown below,
The basic idea behind the usage of the above code is that numbers are displayed as per the fixed length. As you can see, there are only two zeros after the specified number. This is the standard format employed by users after a currency value.
It is also possible to force the compiler to display a specified number of zeros by specifying the format specifiers as mentioned above with numbers. These are called precision specifiers where the output is displayed based on the number we specify.
Let us see how it works. Copy and save the following code.
  1. using System;  
  2. class NumberDemo_2  
  3. {  
  4.     public static void Main()   
  5.   {  
  6.         int x = 234785;  
  7.         Console.WriteLine("{0:C3}", x);  
  8.         Console.WriteLine("{0:D3}", x);  
  9.         Console.WriteLine("{0:E3}", x);  
  10.         Console.WriteLine("{0:F3}", x);  
  11.         Console.WriteLine("{0:G3}", x);  
  12.         Console.WriteLine("{0:N3}", x);  
  13.         Console.WriteLine("{0:X3}", x);  
  14.         Console.WriteLine("{0:x3}", x);  
  15.     }  
  16. }  
You should then compile and execute the program as usual. You will view an output as shown below,
As you can see, we have specified C3 in the first statement of the above code. That’s why there are three zeros after the decimal point. You can modify the statements by adding C5, C8 and observe the output.
In the next FAQ, we will examine the various ways to display date and time.