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 ...

Get C# Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.