How to: Convert a String to a Number
You can convert a string to a number by using methods in the Convert class or by using the TryParse
method found on the various numeric types (int, long, float, etc.).
If you have a string, it is slightly more efficient and straightforward to call a TryParse
method (for example, int.TryParse("11", out number)
). Using a Convert method is more useful for general objects that implement IConvertible.
You can use Parse
or TryParse
methods on the numeric type you expect the string contains, such as the System.Int32 type. The Convert.ToUInt32 method uses Parse internally. If the string is not in a valid format, Parse
throws an exception whereas TryParse
returns false.
Example
The Parse
and TryParse
methods ignore white space at the beginning and at the end of the string, but all other characters must be characters that form the appropriate numeric type (int, long, ulong, float, decimal, etc.). Any white space within the characters that form the number cause an error. For example, you can use decimal.TryParse
to parse "10", "10.3", " 10 ", but you cannot use this method to parse 10 from "10X", "1 0" (note space), "10 .3" (note space), "10e1" (float.TryParse
works here), and so on.
The examples below demonstrate both successful and unsuccessful calls to Parse
and TryParse
.
using System;
using System.Text;
int numVal = Int32.Parse("-105");
Console.WriteLine(numVal);
// Output: -105
// TryParse returns true if the conversion succeeded
// and stores the result in j.
int j;
if (Int32.TryParse("-105", out j))
Console.WriteLine(j);
else
Console.WriteLine("String could not be parsed.");
// Output: -105
try
{
int m = Int32.Parse("abc");
}
catch (FormatException e)
{
Console.WriteLine(e.Message);
}
// Output: Input string was not in a correct format.
string inputString = "abc";
int numValue;
bool parsed = Int32.TryParse(inputString, out numValue);
if (!parsed)
Console.WriteLine("Int32.TryParse could not parse '{0}' to an int.\n", inputString);
// Output: Int32.TryParse could not parse 'abc' to an int.
// This snippet shows a couple of examples that extract number characters from the
// beginning of the string to avoid TryParse errors.
StringBuilder sb = new StringBuilder();
var str = " 10FFxxx";
foreach (char c in str) {
// Check for numeric characters (hex in this case). Add "." and "e" if float,
// and remove letters. Include initial space because it is harmless.
if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f') || c == ' ') {
sb.Append(c);
}
else
break;
}
if (int.TryParse(sb.ToString(), System.Globalization.NumberStyles.HexNumber, null, out int i))
Console.WriteLine(sb.ToString());
str = " -10FFXXX";
sb.Clear();
foreach (char c in str) {
// Check for numeric characters (allow negative in this case but no hex digits).
// Though we use int.TryParse in the previous example and this one, int.TryParse does NOT
// allow a sign character (-) AND hex digits at the same time.
// Include initial space because it is harmless.
if ((c >= '0' && c <= '9') || c == ' ' || c == '-') {
sb.Append(c);
} else
break;
}
if (int.TryParse(sb.ToString(), out int j))
Console.WriteLine(sb.ToString());
Example
The following table lists some of the methods from the Convert class that you can use.
Numeric Type | Method |
---|---|
decimal |
ToDecimal(String) |
float |
ToSingle(String) |
double |
ToDouble(String) |
short |
ToInt16(String) |
int |
ToInt32(String) |
long |
ToInt64(String) |
ushort |
ToUInt16(String) |
uint |
ToUInt32(String) |
ulong |
ToUInt64(String) |
This example calls the Convert.ToInt32(String) method to convert an input string to an int . The code catches the two most common exceptions that can be thrown by this method, FormatException and OverflowException. If the number can be incremented without overflowing the integer storage location, the program adds 1 to the result and prints the output.
using System;
using System.Text;
static void Main(string[] args)
{
int numVal = -1;
bool repeat = true;
while (repeat)
{
Console.WriteLine("Enter a number between −2,147,483,648 and +2,147,483,647 (inclusive).");
string input = Console.ReadLine();
// ToInt32 can throw FormatException or OverflowException.
try
{
numVal = Convert.ToInt32(input);
}
catch (FormatException e)
{
Console.WriteLine("Input string is not a sequence of digits.");
}
catch (OverflowException e)
{
Console.WriteLine("The number cannot fit in an Int32.");
}
finally
{
if (numVal < Int32.MaxValue)
{
Console.WriteLine("The new value is {0}", numVal + 1);
}
else
{
Console.WriteLine("numVal cannot be incremented beyond its current value");
}
}
Console.WriteLine("Go again? Y/N");
string go = Console.ReadLine();
if (go == "Y" || go == "y")
{
repeat = true;
}
else
{
repeat = false;
}
}
// Keep the console open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
// Sample Output:
// Enter a number between -2,147,483,648 and +2,147,483,647 (inclusive).
// 473
// The new value is 474
// Go again? Y/N
// y
// Enter a number between -2,147,483,648 and +2,147,483,647 (inclusive).
// 2147483647
// numVal cannot be incremented beyond its current value
// Go again? Y/N
// Y
// Enter a number between -2,147,483,648 and +2,147,483,647 (inclusive).
// -1000
// The new value is -999
// Go again? Y/N
// n
// Press any key to exit.