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.

Literal Characters

Often numeric values need to be formatted to include non-numeric characters. This can be achieved by inserting the characters into the picture format. To insert placeholder characters such as those described in the previous sections, enclose them in apostrophes (') or quotes ("). For ease of reading, the following example uses apostrophes.

Console.WriteLine(12345.ToString("00-00-00"));     // Outputs "01-23-45"
Console.WriteLine(12345.ToString("0'E'"));         // Outputs "12345E"

Escape Characters

Escape characters may also be used in picture format strings. These use the standard backslash character to identify an escape sequence. This backslash must appear in the format string itself so must be inserted using a double-backslash if the picture format is not preceded by an '@'. To insert a backslash character into the final string, four backslashes must be included in the picture format.

Console.WriteLine(123.45.ToString("\\'0.00\\'"));  // Outputs "'123.45'"
Console.WriteLine(12345.ToString("000\\\\000"));   // Outputs "012\345"

Section Separator Character

The final special character that can be inserted into a picture format is the section separator. This allows different formatting to be used for positive, negative and zero values. If a single semicolon (;) character is included the format to the left of the semicolon is used for positive values and the format to the right for negative numbers. Adding a second section separator creates a third section for zero values. If the second section is empty the positive and negative formats will both use the formatting from the first section.

Console.WriteLine(1.ToString("0.0;(0.0)"));         // Outputs "1.0"
Console.WriteLine((-1).ToString("0.0;(0.0)"));      // Outputs "(1.0)"

Console.WriteLine(1.ToString("0.0;(0.0);#.#"));     // Outputs "1.0"
Console.WriteLine((-1).ToString("0.0;(0.0);#.#"));  // Outputs "(1.0)"
Console.WriteLine(0.ToString("0.0;(0.0);#.#"));     // Outputs an empty string

Console.WriteLine(1.ToString("0.0;;#.#"));          // Outputs "1.0"
Console.WriteLine((-1).ToString("0.0;;#.#"));       // Outputs "-1.0"
Console.WriteLine(0.ToString("0.0;;#.#"));          // Outputs an empty string
12 November 2006