Some Output Options


Up to this point, when data has been output using a WriteLine( ) statement, it has been displayed using the default format provided by C#. However, C# defines a sophisticated formatting mechanism that gives you detailed control over how data is displayed. Although formatted I/O is covered in detail later in this book, it is useful to introduce some formatting options at this time. Using these options, you will be able to specify the way values look when output via a WriteLine( ) statement. Doing so enables you to produce more appealing output. Keep in mind that the C# formatting mechanism supports many more features than described here.

When outputting lists of data, you have been separating each part of the list with a plus sign, as shown here:

 Console.WriteLine("You ordered " + 2 + " items at $" + 3 + " each.");

While very convenient, outputting numeric information in this way does not give you any control over how that information appears. For example, for a floating-point value, you can’t control the number of decimal places displayed. Consider the following statement:

 Console.WriteLine("Here is 10/3: " + 10.0/3.0);

It generates this output:

 Here is 10/3: 3.33333333333333

While this might be fine for some purposes, displaying so many decimal places could be inappropriate for others. For example, in financial calculations, you will usually want to display two decimal places.

To control how numeric data is formatted, you will need to use a second form of WriteLine( ), shown here, which allows you to embed formatting information:

 WriteLine(“format string”, arg0, arg1,  , argN);

In this version, the arguments to WriteLine( ) are separated by commas and not + signs. The format string contains two items: regular, printing characters that are displayed as-is, and format specifiers. Format specifiers take this general form:

 {argnum, width: fmt}

Here, argnum specifies the number of the argument (starting from zero) to display. The minimum width of the field is specified by width, and the format is specified by fmt.

During execution, when a format specifier is encountered in the format string, the corresponding argument, as specified by argnum, is substituted and displayed. Thus, it is the position of a format specification within the format string that determines where its matching data will be displayed. Both width and fmt are optional. Therefore, in its simplest form, a format specifier simply indicates which argument to display. For example, {0} indicates arg0, {1} specifies arg1, and so on.

Let’s begin with a simple example. The statement

 Console.WriteLine("February has {0} or {1} days.", 28, 29);

produces the following output:

 February has 28 or 29 days.

As you can see, the value 28 is substituted for {0}, and 29 is substituted for {1}. Thus, the format specifiers identify the location at which the subsequent arguments, in this case 28 and 29, are displayed within the string. Furthermore, notice that the additional values are separated by commas, not + signs.

Here is a variation of the preceding statement that specifies minimum field widths:

 Console.WriteLine("February has {0,10} or {1,5} days.", 28, 29);

It produces the following output:

 February has         28 or    29 days.

As you can see, spaces have been added to fill out the unused portions of the fields. Remember, a minimum field width is just that: the minimum width. Output can exceed that width if needed.

Of course, the arguments associated with a format command need not be constants. For example, this program displays a table of squares and cubes. It uses format commands to output the values.

 // Use format commands. using System; class DisplayOptions {   public static void Main() {     int i;     Console.WriteLine("Value\tSquared\tCubed");     for(i = 1; i < 10; i++)       Console.WriteLine("{0}\t{1}\t{2}",                         i, i*i, i*i*i);   } }

The output is shown here:

 Value   Squared Cubed 1       1       1 2       4       8 3       9       27 4       16      64 5       25      125 6       36      216 7       49      343 8       64      512 9       81      729

In the preceding examples, no formatting was applied to the values, themselves. Of course, the purpose of using format specifiers is to control the way the data looks. The types of data most commonly formatted are floating-point and decimal values. One of the easiest ways to specify a format is to describe a template that WriteLine( ) will use. To do this, show an example of the format that you want, using #s to mark the digit positions. You can also specify the decimal point and commas. For example, here is a better way to display 10 divided by 3:

 Console.WriteLine("Here is 10/3: {0:#.##}", 10.0/3.0);

The output from this statement is shown here:

 Here is 10/3: 3.33

In this example, the template is #.##, which tells WriteLine( ) to display two decimal places. It is important to understand, however, that WriteLine( ) will display more than one digit to the left of the decimal point, if necessary, so as not to misrepresent the value.

Here is another example. This statement

 Console.WriteLine("{0:###,###.##}", 123456.56);

generates this output:

 123,456.56

If you want to display values using a dollars and cents format, use the C format specifier. For example:

 decimal balance; balance = 12323.09m; Console.WriteLine("Current balance is {0:C}", balance);

The output from this sequence is shown here:

 Current balance is $12,323.09

The C format can be used to improve the output from the price discount program shown earlier:

 /*    Use the C format specifier to output dollars and cents. */ using System; class UseDecimal {   public static void Main() {     decimal price;     decimal discount;     decimal discounted_price;     // compute discounted price     price = 19.95m;     discount = 0.15m; // discount rate is 15%     discounted_price = price - ( price * discount);     Console.WriteLine("Discounted price: {0:C}", discounted_price);   } }

Here is the way the output now looks:

 Discounted price: $16.96




C# 2.0(c) The Complete Reference
C# 2.0: The Complete Reference (Complete Reference Series)
ISBN: 0072262095
EAN: 2147483647
Year: 2006
Pages: 300

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net