Information Technology Reference
In-Depth Information
Formatting Numeric Strings
Throughout the text, I have used the WriteLine method to display values. Each time, I used the
simple substitution marker consisting of curly braces surrounding an integer. Many times,
however, you will want to present the output of a text string in a format more appropriate than
just a plain number. For example, you might want to display a value as currency, or as a fixed-
point value with a certain number of decimal places. You can do this by using format strings.
For example, the following code consists of two statements that print out the value 500.
The first line prints out the number without any additional formatting. In the second line, the
format string specifies that the number should be formatted as currency.
Console.WriteLine("The value: {0}." , 500); // Print out number.
Console.WriteLine("The value: { 0:C} .", 500); // Format as currency.
Format as currency.
This code produces the following output.
The value: 500.
The value: $500.00.
The difference between the two statements is that the format item includes additional
information in the form of a format specifier. The syntax for a format specifier consists of three
fields inside the set of curly braces: the index, the alignment specifier, and the format specifier.
The syntax is shown in Figure 23-1.
Figure 23-1. Syntax for a format item
The first thing in the format item is the index. As you well know by now, the index specifies
which item from the list, following the format string, should be formatted. The index is required,
and numbering of the list items starts at 0.
Search WWH ::




Custom Search