BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

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

Available Format Specifiers

The full list of format specifiers and the effect of the precision specifier for each is as follows:

SpecifierDescriptionEffect of Precision Specifier
C or cFormats the number as a monetary value including the correct number of decimal places and the appropriate currency symbol for the user's local settingSpecifies a fixed number of decimal places.
D or dFormats integers only as simple whole numbers.Specifies the minimum number of digits. Leading zeroes are added if required.
EFormats numbers using exponential notation. The resultant string includes an upper case letter 'E'.Specifies a fixed number of decimal places for the mantissa. If omitted, six decimal places are used.
eFormats numbers using exponential notation. The resultant string includes a lower case letter 'e'.Specifies a fixed number of decimal places for the mantissa. If omitted, six decimal places are used.
F or fFormats numbers using fixed-point notation.Specifies a fixed number of decimal places.
G or gFormats numbers using either exponential or fixed-point notation, whichever produces the shortest string. The actual results vary according to the data type being converted and whether a precision specifier is used.See 'e', 'E' and 'F or f'.
N or nFormats numbers using fixed-point notation with thousands separators.Specifies a fixed number of decimal places.
P or pFormats numbers using percentage notation. For example, 0.25 is formatted as 25%.Specifies a fixed number of decimal places.
R or rFormats numbers using Round-Trip Format. This is a special format that ensures that the string generated can be converted back to the original number using Parse methods.Unused.
XConverts numbers into a string representation of their hexadecimal value. The digits 0 to 9 and A to F are used.Specifies the minimum number of digits. Leading zeroes are added if required.
xConverts numbers into a string representation of their hexadecimal value. The digits 0 to 9 and a to f are used.Specifies the minimum number of digits. Leading zeroes are added if required.

Using Picture Formats for Custom Formatting

The standard format specifiers are useful in most situations. However, there may be circumstances where the format specifiers do not provide the desired results. In these cases you can use a picture format. A picture format is a string containing special characters that affect the final conversion. There are a number of control characters; each will be considered in the following sections.

12 November 2006