C#: How to Convert a Numeric String to Int/Double

Updated: February 12, 2023 By: Pennywise Post a comment

This article walks you through a few examples of converting a numeric string to an integer or a double in C#.

Converting Numeric Strings to Integers

Using Parse and TryParse Methods

You can use the following methods to parse numeric strings to integers:

  • Int16.Parse, Int16.TryParse: Return a 16-bit integer
  • Int32.Parse, Int32.TryParse: Return a 32-bit integer
  • Int64.Parse, Int64.TryParse: Return a 64-bit integer

The difference between the Parse() and TryParse() methods is that TryParse() always returns a value, and it will never throw an exception as Parse(). If the input is an invalid numeric string, TryParse will return 0.

Example:

String x1 = "123"; // This is a valid numeric string

Int32 y1 = Int32.Parse(x1);
Int16 z1 = Int16.Parse(x1);
Int64 t1 = Int64.Parse(x1);

Console.WriteLine($"y1 type: {y1.GetType()}, z1 type: {z1.GetType()}, t1 type: {t1.GetType()}");

Output:

y1 type: System.Int32, z1 type: System.Int16, t1 type: System.Int64

Another example:

String x2 = "ABC"; // This is an invalid numeric string

Int32 y2;
Int16 z2;
Int64 t2;

Int32.TryParse(x2, out y2);
Int16.TryParse(x2, out z2);
Int64.TryParse(x2, out t2);

Console.WriteLine($"y2:{y2}, z2: {z2}, t2: {t2}");

Output:

y2:0, z2: 0, t2: 0

Using Convert.ToInt32, Convert.ToInt16, Convert.ToInt64 Methods

Example:

String input1 = "333";
String input2 = "112";
String input3 = "-444";

Int16 output1 = Convert.ToInt16(input1);
Int32 output2 = Convert.ToInt32(input2);
Int64 output3 = Convert.ToInt64(input3);

Console.WriteLine("Output 1:" + output1.GetType());
Console.WriteLine("Output 2:" + output2.GetType());
Console.WriteLine("Output 3:" + output3.GetType());

Output:

Output 1:System.Int16
Output 2:System.Int32
Output 3:System.Int64

Converting Numeric Strings to Doubles

Using Parse and TryParse Methods

You can use the Double.Parse or Double.TryParse methods to convert a numeric string to a double.

Example:

String a = "1.234";
String b = "-456";

Double outputA = Double.Parse(a);

Double outputB;
Double.TryParse(b, out outputB);

Console.WriteLine("outputA type: " + outputA.GetType());
Console.WriteLine("outputB type:" + outputB.GetType());

Output:

outputA type: System.Double
outputB type:System.Double

Using Convert.ToDouble Method

Example:

String input = "-1.222333222";

Double output = Convert.ToDouble(input);
Console.WriteLine(output.GetType());

Output:

System.Double

Conclusion

This article covered a couple of different approaches to converting numeric strings to integers and doubles. If you’d like to explore more new and interesting things about C# and related stuff, take a look at the following articles:

You can also check out our C Sharp and Unity 3d topic page to see the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles