C# String to Number Conversion
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.
Converting Strings to Numeric Data Types
User input is often provided using unrestricted textboxes; the entered information becomes the contents of a string. If the textbox is being used to specify a number, the string may require conversion to a numeric data type.
In a previous article, we discussed implicit and explicit conversion between numeric types using the cast functions. Casting is unavailable when converting between strings and numeric values. Instead, the .NET framework provides a 'Convert' class specifically designed for converting between native types. The numeric types also provide methods for parsing strings.
The Convert class is found in the System namespace. It provides conversion functions as static methods. Static methods will be described in a later tutorial. For the purposes of the C# Fundamentals tutorial, it is enough to understand static methods are called without first creating an object. In other words, you do not need to create a Convert object to access the methods we require.
.NET Structures and C# Keywords
One complication when using the Convert class is that native C# data types are named differently than the underlying .NET framework structures. The following table lists the numeric and Boolean data types that have been described in the tutorial and the corresponding .NET names. The Convert class uses the case-sensitive .NET names.
|C# Data Type||.NET Structure Name|
The static conversion methods follow a standardised syntax. The method name starts with 'To' followed by the desired .NET data type name. For example, to convert a string to a float, the method called is Convert.ToSingle. The string value to be converted is provided as a parameter.
// Convert a string to an integer
int stringToInt = Convert.ToInt32("25");
// Convert a string to a decimal
decimal stringToDecimal = Convert.ToDecimal("25.5");
// Booleans can be converted too
bool stringToBoolean = Convert.ToBoolean("true");
NB: The Convert method can be used without a reference to the System namespace because Visual Studio automatically includes the following line at the top of the code file:
The using statement tells the compiler which namespaces should be searched for classes automatically. Without this command, the namespace must be included. As namespaces can have long names, this can become difficult to read. Without the using directive, the code would be:
int stringToInt = System.Convert.ToInt32("25");
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
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
11 November 2006