Creating a Custom Numeric Format


Although the predefined numeric format specifiers are quite useful, C# gives you the ability to define your own custom format using a feature sometimes called picture format. The term picture format comes from the fact that you create a custom format by specifying an example (that is, picture) of how you want the output to look. This approach was mentioned briefly in Part I. Here it is examined in detail.

The Custom Format Placeholder Characters

When you create a custom format, you specify that format by creating an example (or picture) of what you want the data to look like. To do this, use the characters shown in Table 21-6 as placeholders. Each is examined in turn.

Table 21-6: Custom Format Placeholder Characters

Placeholder

Meaning

#

Digit.

.

Decimal point.

,

Thousands separator.

%

Percentage, which is the value being formatted multiplied by 100.

0

Pads with leading and trailing zeros.

;

Separates sections that describe the format for positive, negative, and zero values.

E0 E+0 E-0

e0 e+0 e-0

Scientific notation.

The period specifies where the decimal point will be located.

The # placeholder specifies a digit position. The # can occur on the left or right side of the decimal point, or by itself. When one or more #s occur on the right side of the decimal point, they specify the number of decimal digits to display. The value is rounded if necessary.

When the # occurs to the left of the decimal point, it specifies the digit positions for the whole-number part of the value. Leading zeros will be added if necessary. If the whole-number portion of the value has more digits than there are #s, the entire whole-number portion will be displayed. In no cases will the whole-number portion of a value be truncated. If there is no decimal point, then the # causes the value to be rounded to its integer value. A zero value that is not significant, such as a trailing zero, will not be displayed. This causes a somewhat odd quirk, however, because a format such as ##.## displays nothing at all if the value being formatted is zero. To output a zero value, use the 0 placeholder described next.

The 0 placeholder causes a leading or trailing 0 to be added to ensure that a minimum number of digits will be present. It can be used on both the right and left side of the decimal point. For example:

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

displays this output:

 0021.300

Values containing more digits will be displayed in full on the left side of the decimal point and rounded on the right side.

You can insert commas into large numbers by specifying a pattern that embeds a comma within a sequence of #s. For example, this:

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

displays

 3,421.3.

It is not necessary to specify a comma for each position. Specifying one comma causes it to be inserted into the value every third digit from the left. For example:

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

produces this output:

 8,763,421.3.

Commas have a second meaning. When they occur on the immediate left of the decimal point, they act as a scaling factor. Each comma causes the value to be divided by 1,000. For example:

 Console.WriteLine("Value in thousands: {0:#,###,.#}", 8763421.3);

produces this output:

 Value in thousands: 8,763.4

As the output shows, the value is scaled in terms of thousands.

In addition to the placeholders, a custom format specifier can contain other characters. Any other characters are simply passed through, appearing in the formatted string exactly as they appear in the format specifier. For example, this WriteLine( ) statement:

 Console.WriteLine("Fuel efficiency is {0:##.# mpg}", 21.3);

produces this output:

 Fuel efficiency is 21.3 mpg

You can also use the escape sequences, such as \t or \n, if necessary.

The E and e placeholders cause a value to be displayed in scientific notation. At least one 0, but possibly more, must follow the E or e. The 0’s indicate the number of decimal digits that will be displayed. The decimal component will be rounded to fit the format. Using an uppercase E causes an uppercase E to be displayed; using a lowercase e causes a lowercase e to be displayed. To ensure that a sign character precedes the exponent, use the E+ or e+ forms. To display a sign character for negative values only, use E, e, E-, or e-.

The “;” is a separator that enables you to specify different formats for positive, negative, and zero values. Here is the general form of a custom format specifier that uses the “;”:

 positive-fmt;negative-fmt;zero-fmt 

Here is an example:

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

If num is positive, the value is displayed with two decimal places. If num is negative, the value is displayed with two decimal places and is between a set of parentheses. If num is zero, the string 0.00 is displayed. When using the separators, you don’t need to supply all parts. If you just want to specify how positive and negative values will look, omit the zero format. To use the default for negative values, omit the negative format. In this case, the positive format and the zero format will be separated by two semicolons.

The following program demonstrates just a few of the many possible custom formats that you can create:

 // Using custom formats. using System; class PictureFormatDemo {   public static void Main() {     double num = 64354.2345;     Console.WriteLine("Default format: " + num);     // Display with 2 decimal places.     Console.WriteLine("Value with two decimal places: " +                       "{0:#.##}", num);     // Display with commas and 2 decimal places.     Console.WriteLine("Add commas: {0:#,###.##}", num);     // Display using scientific notation.     Console.WriteLine("Use scientific notation: " +                       "{0:#.###e+00}", num);     // Scale the value by 1000.     Console.WriteLine("Value in 1,000s: " +                       "{0:#0,}", num);     /* Display positive, negative, and zero        values differently. */     Console.WriteLine("Display positive, negative, " +                       "and zero values differently.");     Console.WriteLine("{0:#.#;(#.##);0.00}", num);     num = -num;     Console.WriteLine("{0:#.##;(#.##);0.00}", num);     num = 0.0;     Console.WriteLine("{0:#.##;(#.##);0.00}", num);     // Display a percentage.     num = 0.17;     Console.WriteLine("Display a percentage: {0:#%}", num);   } } 

The output is shown here:

 Default format: 64354.2345 Value with two decimal places: 64354.23 Add commas: 64,354.23 Use scientific notation: 6.435e+04 Value in 1,000s: 64 Display positive, negative, and zero values differently. 64354.2 (64354.23) 0.00 Display a percentage: 17%




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