Here you will learn how to convert a numeric string to the integer type.
In C#, you can convert a string representation of a number to an integer using the following ways:
- Parse() method
- Convert class
- TryParse() method - Recommended
Parse Method
The Parse()
methods are available for all the primitive datatypes. It is the easiest way to convert from string to integer.
The Parse methods are available for 16, 32, 64 bit signed integer types:
Parse(string s, numberstyle style)
Parse(String s, NumberStyles style, IFormatProvider provider)
It takes up to 3 parameters, a string which is mandatory to convert string to integer format, the second parameter contains the number style which specifies the style of the number to be represented, and the third parameter represents string cultural-specific format.
The following example demonstrates converting numeric strings to integers.
Int16.Parse("100"); // returns 100
Int16.Parse("(100)", NumberStyles.AllowParentheses); // returns -100
int.Parse("30,000", NumberStyles.AllowThousands, new CultureInfo("en-au"));// returns 30000
int.Parse("$ 10000", NumberStyles.AllowCurrencySymbol); //returns 10000
int.Parse("-100", NumberStyles.AllowLeadingSign); // returns -100
int.Parse(" 100 ", NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite); // returns 100
Int64.Parse("2147483649"); // returns 2147483649
As you can see in the above example, a valid numeric string can be converted to an integer. The Parse()
method allows conversion of the numeric string into different formats into an integer using the NumberStyles
enum e.g string with parentheses, culture-specific numeric string, with a currency symbol, etc.
However, the passed string must be a valid numeric string or in the range of the type on which they are being called. The following statements throw exceptions.
int.Parse(null);//thows FormatException
int.Parse("");//thows FormatException
int.Parse("100.00"); // throws FormatException
int.Parse( "100a"); //throws formatexception
int.Parse(2147483649);//throws overflow exception use Int64.Parse()
Pros:
- Converts valid numeric string to integer value.
- Supports different number styles.
- Supports culture-specific custom formats.
Cons:
- Input string must be a valid numeric string.
- The numeric string must be within the range of int type on which the method is called.
- Throws exception on converting null or invalid numeric string.
Convert Class
Another way to convert string to integer is by using static Convert class. The Convert class includes different methods which convert base data type to another base data type.
The Convert class includes the following methods to convert from different data types to int type.
The Convert.ToInt16()
method returns the 16-bit integer e.g. short, the Convert.ToInt32()
returns 32-bit integers e.g. int and
the Convert.ToInt64()
returns the 64-bit integer e.g. long.
Convert.ToInt16("100"); // returns short
Convert.ToInt16(null);//returns 0
Convert.ToInt32("233300");// returns int
Convert.ToInt32("1234",16); // returns 4660 - Hexadecimal of 1234
Convert.ToInt64("1003232131321321");//returns long
// the following throw exceptions
Convert.ToInt16("");//throws FormatException
Convert.ToInt32("30,000"); //throws FormatException
Convert.ToInt16("(100)");//throws FormatException
Convert.ToInt16("100a"); //throws FormatException
Convert.ToInt16(2147483649);//throws OverflowException
Pros:
- Converts from any data type to integer.
- Converts null to 0, so not throwing an exception.
Cons:
- Input string must be valid number string, cannot include different numeric formats. Only works with valid integer string.
-
Input string must be within the range of called
IntXX
method e.g. Int16, Int32, Int64. - The input string cannot include parenthesis, comma, etc.
-
Must use a different method for different integer ranges e.g. cannot use the
Convert.ToInt16()
for the integer string higher than "32767".
Visit Convert class for more information.
TryParse Method
The TryParse()
methods are available for all the primitive types to convert string to the calling data type. It is the recommended way to convert string to an integer.
The TryParse()
method converts the string representation of a number to its 16, 32, and 64-bit signed integer equivalent.
It returns boolean which indicates whether the conversion succeeded or failed and so it never throws exceptions.
The TryParse()
methods are available for all the integer types:
bool Int32.TryParse(string s, NumberStyle style, IFormatProvider provider, out int result)
The TryParse()
method takes 3 parameters identical to the Parse()
method having the same functionality.
The following example demonstrates the TryParse()
method.
string numberStr = "123456";
int number;
bool isParsable = Int32.TryParse(numberStr, out number);
if (isParsable)
Console.WriteLine(number);
else
Console.WriteLine("Could not be parsed.");
The following example demonstrates converting invalid numeric string.
string numberStr = "123456as";
int number;
bool isParsable = Int32.TryParse(numberStr, out number);
if (isParsable)
Console.WriteLine(number);
else
Console.WriteLine("Could not be parsed.");
In the above example, numberStr = "123456as"
which is invalid numeric string.
However, Int32.TryParse()
method will return false instead of throwing an exception.
Thus, the TryParse()
method is the safest way to converting numeric string to integer type when we don't know whether the string is a valid numeric string or not.
Pros:
- Converts different numeric strings to integers.
- Converts string representation of different number styles.
- Converts culture-specific numeric strings to integers.
- Never throws an exception. Returns false if cannot parse to an integer.
Cons:
- Must use out parameter.
- Need to write more code lines instead of single method call.
- How to validate email in C#?
- How to get the sizeof a datatype in C#?
- Difference between String and StringBuilder in C#
- Static vs Singleton in C#
- Difference between == and Equals() Method in C#
- Asynchronous programming with async, await, Task in C#
- How to loop through an enum in C#?
- Generate Random Numbers in C#
- Difference between Two Dates in C#
- Convert int to enum in C#
- BigInteger Data Type in C#
- Convert String to Enum in C#
- Convert an Object to JSON in C#
- Convert JSON String to Object in C#
- DateTime Formats in C#
- How to convert date object to string in C#?
- Compare strings in C#
- How to count elements in C# array?
- Difference between String and string in C#.
- How to get a comma separated string from an array in C#?
- Boxing and Unboxing in C#