BlackWaspTM
C# Programming
.NET 1.1+

C# String to Number Conversion (2)

The eighteenth part of the C# Fundamentals tutorial brings together the native data types discussed so far. This article describes how to convert string values to numeric types. This is essential when allowing free-form user input of numeric data.

Numeric Conversions with Convert

The Convert class can also be used to convert between numeric types. Where a floating-point number is converted to an integer, the result is rounded to the nearest whole number, unlike casting where the decimal part is truncated. However, unlike the standard rules of mathematical rounding, if the floating-point number is exactly half way between two integers the nearest even number is returned.

decimal originalValue = 25.5M;
int converted = Convert.ToInt32(originalValue);     // Result is 26
int casted = (int)originalValue;                    // Result is 25

Parse Method

The numeric types provide a Parse method that converts strings into numbers. This provides additional flexibility by allowing the developer to specify the style of number being converted. For example, allowing the use of currency symbols or hexadecimal numbers.

The Parse method is overloaded, meaning that there are several ways to call the method, each with different parameters. We will examine two overloads in this article. The first takes a single string parameter holding the string to convert:

string toConvert = "100";
int convertedInt = int.Parse(toConvert);            // Result is 100
float convertedFloat = float.Parse(toConvert);      // Result is 100.0

Using Number Styles

The simple manner of calling Parse described above has a drawback. The string containing the number must contain only numeric digits. A number such as "£10,000" causes an exception when parsed. To avoid this, a second parameter can be added to define the permitted number styles for the string's contents. The .NET framework provides an enumeration for allowable number styles. An enumeration is a special value type that contains a named set of available values. Enumerations will be described in detail later in the tutorial.

The NumberStyles enumeration is defined within the System.Globalization namespace. To avoid having to type System.Globalization before every reference to NumberStyles, add a using directive to the start of the code file.

using System.Globalization;

With the using directive added, we can use the NumberStyles enumeration as a second parameter to the Parse method.

// Conversion including thousands separator
int thousands = int.Parse("1,000", NumberStyles.AllowThousands);

// Conversion of value including a decimal point
float withDecimal = float.Parse("5.50", NumberStyles.AllowDecimalPoint);

// Conversion of value including a currency symbol
// (Make sure you change the currency symbol to match your local currency)
int withCurrency = int.Parse("£5", NumberStyles.AllowCurrencySymbol);

The NumberStyles enumeration values can be combined using the OR operator (|), allowing multiple styles. For example:

// Conversion of value including a decimal point and currency symbol
float multiple = float.Parse(
    "£5.50", NumberStyles.AllowDecimalPoint | NumberStyles.AllowCurrencySymbol);

The enumeration provides some predefined styles. The example above used two styles to convert a currency value. We can use the Currency option from the NumberStyles enumeration to permit these styles and more.

// Conversion of a currency value
float money = float.Parse("£9,999.99", NumberStyles.Currency);
11 November 2006