C# Tutorial - Dissecting Our Third Application – Formatting Strings


In our application, we take the value of the total variable and format it into part of the string we see in the console output.

Console.WriteLine("The total is {0}", total);

The first parameter of the WriteLine method is a string literal. This can contain optional placeholders, which allow values to be inserted into the space where the placeholder appears. A placeholder is a pair of curly braces with a number and optional formatters within it. The number within the placeholder refers to the index of the parameter left of the string literal, always starting at zero.

In the above line, the value of the variable total is inserted into the string literal in place of {0}. What this means is that the .NET Framework converts the value of the object to its text representation and embeds that representation into the string. We can show this more clearly by altering the line of code, but not changing the actual output of the code.

Console.WriteLine("The total is {0}", total.ToString());

The ToString() method returns a string that represents the current Object. In this case, the value of the integer variable.

We can change the code to show the user the numbers that they entered as well as the total to demonstrate the use of the placeholders more clearly.

Console.WriteLine("The total of {0} + {1} is {2}",
  value1, value2, total);

If the user entered the numbers 14 and 15, this would give the following output:

The total of 14 + 15 is 29

In general, it does not matter what type of object is passed in as the parameter after the string literal, the .NET Framework will make the necessary conversion to format the object into the string.

String Formatters

A string can be formatted by either using String.Format or by any method that uses string-formatting techniques for parameters such as Console.WriteLine. The formatting for both String.Format and Console.WriteLine are governed by the same formatting rules. Each format item takes the following form:

{index[,alignment][:formatString]}

The index component is mandatory. It is a number starting from zero that identifies a corresponding element in the list of values to the left of the string literal.

The optional alignment component is a signed integer indicating the formatted field width. If this number is negative, the formatted value is left-justified; if this number is positive, the value is right-justified. If padding is necessary, white space is used. To specify alignment, the comma is required.

The optional formatString component consists of a colon along with a standard or custom format specifier. If no specifier is used, then the general (G) format specifier is applied.

Standard Numeric Format Strings

Standard numeric format strings are used to format common numeric types.

Format specifier Name Description
C or c Currency Currency in a culturally aware format. For example, a dollar sign [$] for U.S. English.
D or d Decimal Only supports integral numbers. Displays a string using decimal digits preceded by a minus sign if negative.
E or e Exponential/scientific notation The number is converted to a string of the form "-d.ddd…E+ddd" or "-d.ddd…e+ddd", where each 'd' indicates a digit (0-9).
F or f Fixed point The number is converted to a string of the form "-ddd.ddd…" where each 'd' indicates a digit (0-9).
G or g General format Displays either as a fixed-point or scientific notation based on the size of the number.
N or n Number format The number is converted to a string of the form "-d,ddd,ddd.ddd…", where each 'd' indicates a digit (0-9).
P or p Percentage Multiplies the number by 100 and displays with a percent symbol.
R or r Roundtrip Formats a floating-point number so that it can be successfully converted back to its original value.
X or x Hexadecimal The number is converted to a string of hexadecimal digits.

For example the following code:

Console.WriteLine("{0,-10:D6} {1,-10:D6}", 123, 6789);

Gives the output

000123     006789

<< Previous Contents Next >>

© Publicjoe, 2008