BlackWaspTM
C# Programming
.NET 1.1+

C# Number to String Conversion

The nineteenth part of the C# Fundamentals tutorial continues the examination of conversion between string data and numeric data. This article considers the reverse of the previous part, this time transforming numeric data into formatted strings.

Converting Numeric Values To String Data

The previous article, "C# String to Number Conversion", described how to convert strings into numeric data. This is particularly of use when accepting numeric input from a user. Similarly, it is important to convert numeric data to string information when outputting to screen, printer or other devices.

ToString Method

Every data type and class in the .NET framework includes the ToString method. This returns a string representation of the value or object that the method is executed against. Some classes generate objects that are not easily represented as strings. In these cases the ToString method generally returns the class' fully qualified name, which contains the namespace and type name. For example:

object anObject = new object();
Console.WriteLine(anObject.ToString());            // Outputs "System.Object"

Basic Numeric Conversion Using ToString

The simplest method to convert numbers to strings is using the ToString method for the type with no parameters. The string produced contains the unformatted number. This method can be used on variables and literals.

int quantity = 1500;
float price = 1.50F;
bool sold = true;

Console.WriteLine(quantity.ToString());            // Outputs "1500"
Console.WriteLine(price.ToString());               // Outputs "1.5"
Console.WriteLine(sold.ToString());                // Outputs "True"

Formatting Converted Numbers

When displaying values to a user you should format them appropriately for their purpose and according to the user's local settings. The ToString method permits you to add format specifiers that define this formatting. The format specifiers are supplied in a string parameter.

NB: The following example assumes that the code is executing on a UK machine. The results in other countries may differ.

int quantity = 1500;
float price = 1.50F;
float discount = 0.05F;

Console.WriteLine(quantity.ToString("n0"));        // Outputs "1,500"
Console.WriteLine(price.ToString("c"));            // Outputs "£1.50"
Console.WriteLine(discount.ToString("p1"));        // Outputs "5.0 %"

The three specifiers used in the above examples provide fixed-point notation (n), currency (c) and percentage (p) formatting. In the case of the fixed point and percentage specifier a number is included. This is the precision specifier and is used to modify the format.

12 November 2006