CHAPTER 3 CORE C# PROGRAMMING CONSTRUCTS, PART I
Also know that it is possible to position each placeholder in any location within a string literal, and it
need not follow an increasing sequence. For example, consider the following code snippet:
// Prints: 20, 10, 30
Console.WriteLine("{1}, {0}, {2}", 10, 20, 30);
Formatting Numerical Data
If you require more elaborate formatting for numerical data, each placeholder can optionally contain
various format characters. Table 3-3 shows the most common formatting options.
Table 3-3. .NET Numerical Format Characters
String Format Character
Meaning in Life
C or c
Used to format currency. By default, the flag will prefix the local cultural
symbol (a dollar sign [$] for U.S. English).
D or d
Used to format decimal numbers. This flag may also specify the
minimum number of digits used to pad the value.
E or e
Used for exponential notation. Casing controls whether the exponential
constant is uppercase (E) or lowercase (e).
F or f
Used for fixed-point formatting. This flag may also specify the minimum
number of digits used to pad the value.
G or g Stands
for general. This character can be used to format a number to fixed
or exponential format.
N or n
Used for basic numerical formatting (with commas).
X or x
Used for hexadecimal formatting. If you use an uppercase X, your hex
format will also contain uppercase characters.
These f ormat characters are suffixed to a given placeholder value using the colon token (e.g., {0:C},
{1:d}, {2:X}). To illustrate, update the Main() method to call a new helper function named
FormatNumericalData(). Implement this method in your Program class to format a fixed numerical value
in a variety of ways.
// Now make use of some format tags.
static void FormatNumericalData()
{
Console.WriteLine("The value 99999 in various formats:");
Console.WriteLine("c format: {0:c}", 99999);
Console.WriteLine("d9 format: {0:d9}", 99999);
Console.WriteLine("f3 format: {0:f3}", 99999);
Console.WriteLine("n format: {0:n}", 99999);
84