Team LiB
Previous Section Next Section

String Formatting

The Parse method allows numeric types to be converted from string types. Here is an example:

string X = "12345";
int Y = int.Parse(X);

Parse also has the ability to work with some formatting of strings, such as the following:

string X = "23,456";
int Y = Int.Parse(X, System.Globalization.NumberStyles.AllowThousands);

This example converts the string 23,456 to an int of 23456.

C# provides several built-in ways to format a string. For example, let's say we have an int with a value of 100 and we wish to present this value to the user as currency. We could accomplish this by doing one of the following:

int X = 100;
string Y = int.ToString("C");

or

int X = 100;
Console.WriteLine("{0:C}", X);

Both examples would print $100.00

The following are some of the common formatters:

All of this formatting is built on the globalization settings. You can learn more about string formatting through the following MSDN library articles:


Team LiB
Previous Section Next Section