C# 11 String Formatting

In addition to the wide selection of string manipulation functions outlined in the C# Strings lesson, the string class also provides the  String.Format() method.

The primary purpose of the C#  String.Format() method is to provide a mechanism for inserting string, numerical, or boolean values into a string with additional formatting control.

The Syntax of the String.Format() Method

The general syntax of the String.Format() method is as follows:

String.Format("format string", arg1, arg2, .... ); 

The format string is the string into which the values will be placed. Within this string are placeholders that indicate the location of each value within the string. Placeholders take the form of braces {} surrounding a number indicating the corresponding argument to be substituted for the placeholder. Following on from the format string is a comma-separated list of arguments. There must be an argument for each of the placeholders.

A simple string formatting example

The following code example demonstrates a straightforward use of the  String.Format() method:

string newString;

newString = String.Format("There are {0} cats in my {1} and no {2}", 2, "house", "dogs");

System.Console.WriteLine (newString);

Output:

There are 2 cats in my house and no dogs

Let’s quickly review the String.Format() method call in the above example. The format string contains three placeholders indicated by {0}, {1}, and {2}. Following the format string are the arguments to be used in each placeholder. So, for example, {0} is replaced by the first argument (the number 2), the {1} by the second argument (the string “house”), and so on.

If you cast your mind back to the C# 11 Character and String Data Types chapter, you will probably wonder how this compares to the string interpolation technique we have used countless times throughout the chapter. As we will see below, C# string formatting becomes more useful when combined with format controls.

Using format controls

So far, we have only substituted arguments for placeholders, but we have not changed the format of the arguments before they are displayed. This essentially instructs the Format() method to use the default formatting for each argument type when displaying the string. Perhaps the most powerful aspect of the Format() method is the ability to use format controls within the placeholders to control the output format.

Format controls appear inside the braces ({}) of the placeholders. The format of a placeholder with a format control is as follows:

{n:controlx} 

Where n is the placeholder number and control is the special format control sequence to be applied to the argument. The x optional number further formats the output for certain control types.

A simple format control example

The following example uses the X format control, which is used to display a number using hexadecimal format:

var newString = String.Format("The number {0} in Hexadecimal is {0:X}.", 432);

System.Console.WriteLine (newString);

Output:

The number 432 in Hexadecimal is 1B0.

The above example displays argument 0 (432) in two formats. The first is the default decimal format, while the second uses the X format control to display the argument as a hexadecimal number.

The String.Format() method provides a wide range of format controls which we will explore below.

C# String.Format() format controls

The following table lists format controls supported by the C#  String.Format() method together with examples of each control:

ControlTypeDescriptionExample
CCurrencyDisplays number prefixed with the currency symbol appropriate to the current locale{0:C} of 432.00 outputs $432.00
DDecimalDisplays numbers in decimal form with optional padding{0:D4} of 432 outputs 00432
EExponentialDisplays number in scientific form with optional value for the fractional part{0:E5} of 432.32 outputs 4.32320E+002
FFixedDisplays the number, including the specified number of decimal digits{0:F3} of 432.324343 outputs 432.324
NNumberConverts a number to a human-friendly format by inserting commas and rounding to the nearest 100th{0:N} of 123432.324343 outputs 123,432.32
XHexadecimalConverts a number to hexadecimal{0:X} of 432 outputs 1B0
0:0…Zero PaddingAdds zeros to pad argument{0:0000.00} of 43.1 outputs 0043.10
0:0#…Space PaddingAdds spaces to pad argument{0:####.##} of 43.1 outputs 43.1
%PercentageMultiplies the argument by 100 and appends a percentage sign{0:00.00%} of .432 outputs 43.20%

Before moving on to the next lesson, run the following code to see some of these formats controls in action:

var newString = String.Format("The number {0} fixed to 2 decimal places is {0:F2}.", 109.78799);

System.Console.WriteLine (newString);

newString = String.Format("The number {0} using human friendly formatting is {0:N}.", 1023429.78799);
System.Console.WriteLine (newString);

newString = String.Format("The number {0} using exponential formatting is {0:E6}.", 32423.24232);
System.Console.WriteLine (newString);

newString = String.Format("The number {0} as a percentage to 3 decinal places is {0:00.000%}.", 0.24232);
System.Console.WriteLine (newString);

Output:

The number 109.78799 fixed to 2 decimal places is 109.79.
The number 1023429.78799 using human friendly formatting is 1,023,429.79.
The number 32423.24232 using exponential formatting is 3.242324E+004.
The number 0.24232 as a percentage to 3 decinal places is 24.232%.Code language: CSS (css)

Categories