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,
- using System;
- class Numberdemo
- {
- public static void Main()
- {
- int x = 23456;
- Console.WriteLine("{0:C}", x);
- Console.WriteLine("{0:D}", x);
- Console.WriteLine("{0:E}", x);
- Console.WriteLine("{0:F}", x);
- Console.WriteLine("{0:G}", x);
- Console.WriteLine("{0:N}", x);
- Console.WriteLine("{0:X}", x);
- Console.WriteLine("{0:x}", x);
- }
- }
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.
- using System;
- class NumberDemo_2
- {
- public static void Main()
- {
- int x = 234785;
- Console.WriteLine("{0:C3}", x);
- Console.WriteLine("{0:D3}", x);
- Console.WriteLine("{0:E3}", x);
- Console.WriteLine("{0:F3}", x);
- Console.WriteLine("{0:G3}", x);
- Console.WriteLine("{0:N3}", x);
- Console.WriteLine("{0:X3}", x);
- Console.WriteLine("{0:x3}", x);
- }
- }
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.