DekGenius.com
[ Team LiB ] Previous Section Next Section

Recipe 2.16 Formatting Data in Strings

Problem

You need to format one or more embedded pieces of information inside of a string, such as a number, character, or substring.

Solution

The static string.Format method allows you to format strings in a variety of ways. For example:

int ID = 12345;
double weight = 12.3558;
char row = 'Z';
string section = "1A2C";

string output = string.Format(@"The item ID = {0:G} having weight = {1:G} 
                is found in row {2:G} and section {3:G}", ID, weight, row, section);
Console.WriteLine(output);
output = string.Format(@"The item ID = {0:N} having weight = {1:E} 
                is found in row {2:E} and section {3:E}", ID, weight, row, section);
Console.WriteLine(output);
output = string.Format(@"The item ID = {0:N} having weight = {1:N} 
                is found in row {2:E} and section {3:D}", ID, weight, row, section);
Console.WriteLine(output);
output = string.Format(@"The item ID = {0:(#####)} having weight = {1:0000.00 lbs} 
                    is found in row {2} and section {3}", ID, weight, row, section);
Console.WriteLine(output);

The output is as follows:

The item ID = 12345 having weight = 12.3558 is found in row Z and section 1A2C
The item ID = 12,345.00 having weight = 1.235580E+001 is found in row Z and section 1A2C
The item ID = 12,345.00 having weight = 12.36 is found in row Z and section 1A2C
The item ID = (12345) having weight = 0012.36 lbs is found in row Z and section 1A2C

To simplify things, the string.Format method could be discarded and all the work could have been done in the System.Console.WriteLine method, which calls string.Format internally, as shown here:

Console.WriteLine(@"The item ID = {0,5:G} having weight = {1,10:G} " +
         "is found in row {2,-5:G} and section {3,-10:G}", 
         ID, weight, row, section);

The output of this WriteLine method is:

The item ID = 12345 having weight =    12.3558 is found in row Z     and section 1A2C

Discussion

The string.Format method allows a wide range of formatting options for string data. The first parameter of this method can be passed a string that may look similar to the following:

"The item ID = {0,5:G}"

The text The item ID = will be displayed as is, with no changes. The interesting part of this string is the section enclosed in braces. This section has the following form:

{index, alignment:formatString}

The section can contain the following three parts:


index

A number identifying the zero-based position of the section's data in the args parameter array. The data is to be formatted accordingly and substituted for this section. This number is required.


alignment

The number of spaces to insert before or after this data. A negative number indicates left justification (spaces are added to the right of the data), and a positive number indicates right justification (spaces are added to the left of the data). This number is optional.


formatString

A string indicating the type of formatting to perform on this data. This section is where most of the formatting information usually resides. Tables Table 2-2 and Table 2-3 contain valid formatting codes that can be used here. This part is optional.

Table 2-2. The standard formatting strings

Formatting character(s)

Meaning

C or c

Use the currency format. A precision specifier can optionally follow, indicating the number of decimal places to use.

D or d

Use the decimal format for integral types. A precision specifier can optionally follow, which represents the minimum number of digits in the formatted number.

E or e

Use scientific notation. A precision specifier can optionally follow, indicating the number of digits to use after the decimal point.

F or f

Use fixed-point format. A precision specifier can optionally follow, which represents the number of digits to display to the right of the decimal point.

G or g

Use the general format. The number is displayed in its shortest form. A precision specifier can optionally follow, which represents the number of significant digits to display.

N or n

Use the number format. A minus sign is added to the beginning of a negative number, and thousands separators are placed accordingly in the number. A precision specifier can optionally follow, which represents the number of digits to display to the right of the decimal point.

P or p

Use the percent format. The number is converted to a percent representation of itself. A precision specifier can optionally follow, indicating the number of decimal places to use.

R or r

Use the round-trip format. This format allows the number to be formatted to a representation that can be parsed back to its original form by using the Parse method. Any precision specifier is ignored.

X or x

Use the hexadecimal format. The number is converted to its hexadecimal representation. The uppercase X produces a hexadecimal number with all capital letters A through F. The lowercase x produces a hexadecimal number with all lowercase letters a through f. A precision specifier can optionally follow, which represents the minimum number of digits in the formatted number.

Table 2-3. Custom formatting strings

Formatting character(s)

Meaning

0

Use the zero placeholder format. If a digit in the original number exists in this position, display that digit. If there is no digit in the original string, display a zero.

#

Use the digit placeholder format. If a digit in the original number exists in this position, display that digit. If there is no digit in the original string, display nothing.

.

Use the decimal point format. The decimal point is matched up with the decimal point in the number that is to be formatted. Formatting to the right of the decimal point operates on the digits to the right of the decimal point in the original number. Formatting to the left of the decimal point operates in the same way.

,

Use the thousands separator format. A thousands separator will be placed after every three digits starting at the decimal point and moving to the left.

%

Use the percentage placeholder format. The original number is multiplied by 100 before being displayed.

E or e

Use the scientific notation format. A precision specifier can optionally follow, indicating the number of digits to use after the decimal point.

\

Use the escape character format. The \ character and the next character after it are grouped into an escape sequence.

Any text within single or double quotes such as "aa" or 'aa'

Use no formatting; display as is and in the same position in which the text resides in the format string.

;

Used as a section separator between positive, negative, and zero formatting strings.

Any other character

Use no formatting; display as is and in the same position in which it resides in the format string.

In addition to the string.Format and the Console.WriteLine methods, the overloaded ToString instance method of a value type may also use the previous formatting characters in Table 2-3. Using ToString, the code would look like this:

float valueAsFloat = 122.35;
string valueAsString = valueAsFloat.ToString("[000000.####]");

The valueAsString variable would contain the formatted number contained in valueAsFloat. The formatted number would look like this:

[000122.35]

The overloaded ToString method accepts a single parameter of type IFormatProvider. The IFormatProvider provided for the valueAsFloat.ToString method is a string containing the formatting for the value type plus any extra text that needs to be supplied.

See Also

See the "String.Format Method," "Standard Numeric Format Strings," and "Custom Numeric Format Strings" topics in the MSDN documentation.

    [ Team LiB ] Previous Section Next Section