C# Simplified, part 3 - Displaying numbers in different formats
(Page 2 of 6 )
C# enables you to display numbers in different ways with the help of Format Specifiers. For example, you can display numbers with a currency symbol or with decimal places. These specifiers are enclosed within curly braces followed by the variable name of the specific value.
In Listing 3.2, a variable named i is declared and its value is displayed in different ways using a set of format specifiers. I have given necessary explanations as comments.
Listing 3.2
using System;
class NumberFormat
{
public static void Main()
{
int i = 7777;
// Returns the exact currency value with the symbol ($)
Console.WriteLine("{0:C}",i);
// Returns the Number converted to a string of decimal digits
Console.WriteLine("{0:D}",i);
// Returns the Expotential value
Console.WriteLine("{0:E}",i);
// Returns the fixed point string representation of the number
Console.WriteLine("{0:F}",i);
// Returns the most compact form of fixed point number
Console.WriteLine("{0:G}",i);
// Returns the number in the d,ddd,ddd.ddd format
Console.WriteLine("{0:N}",i);
// Returns the Uppercase hexadecimal digit of the converted number
Console.WriteLine("{0:X}",i);
// Returns the Lowercase hexadecimal digit of the converted number
Console.WriteLine("{0:x}",i);
}
}
The final output of the above program will look like Figure 3.2.

Figure 3.2
Format Specifiers combined with numbers are called Precision Specifiers. For example, if you use a format like C6, you will get six zeros appended after the decimal position of the number. Listing 3.3 shows a modified version of listing 3.2.
Listing 3.3
using System;
class NumberFormatPrecision
{
public static void Main()
{
int i = 7777;
// Returns the exact currency value with the symbol ($)
Console.WriteLine("{0:C5}",i);
// Returns the Number converted to a string of decimal digits
Console.WriteLine("{0:D5}",i);
// Returns the Expotential value
Console.WriteLine("{0:E5}",i);
// Returns the fixed point string representation of the number
Console.WriteLine("{0:F5}",i);
// Returns the most compact form of fixed point number
Console.WriteLine("{0:G5}",i);
// Returns the number in the d,ddd,ddd.ddd format
Console.WriteLine("{0:N5}",i);
// Returns the Uppercase hexadecimal digit of the converted number
Console.WriteLine("{0:X5}",i);
// Returns the Lowercase hexadecimal digit of the converted number
Console.WriteLine("{0:x5}",i);
}
}
The output of the above program looks like Figure 3.3.

Figure 3.3
Next: Display date and time in different formats >>
More C# Articles
More By Anand Narayanaswamy