O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required