How to convert a string to int in C#?

The string to int conversion may be required for different reasons. Commonly, this is required if you are taking the user input for numbers and this may be taken as “text” or string. So, you have to make sure before performing any actions based on that data to convert that string into int, float or other numeric data types.

In  C#, there are different ways of converting a string to int, float, long etc.

  • Parse or TryParse methods
  • Using the Convert class methods e.g. ToDecimal, ToInt16, ToInt32, ToInt64 etc.

The section below shows you how to use these ways for converting the string to numbers.

The example of using Parse/TryParse for string to int conversion

The example below shows converting a string to int by using the Parse method. In the code, a positive and a negative “string” numbers are converted by int32.Parse method:

The Code:

using System;

using System.Text;



class string_to_int

{

    static void Main()

    {

        int posStr = Int32.Parse("55");

        int negStr = Int32.Parse("-155");



        Console.WriteLine("Positive number = " + posStr);

        Console.WriteLine("Negative number = " + negStr);





        Console.ReadLine();

    }

}

The output of above code:

c_string to int

This is how Parse and TryParse methods work:

  • Both ignore the leading and trailing spaces in the given string.
  • If space exists between characters in a string then an error will generate in case of Parse method. If you are using TryParse method then it returns false.
  • The characters in the given string to be converted into numbers must form the appropriate numeric type. For example, “101”, “110.45”.
  • These numbers will produce an error in case of Parse e.g. “1 01”, “110 .45” as a space character exists. In the case of TryParse, it returns false.

The example of converting a decimal string

Similarly, by using the float keyword with Parse method, you may convert a decimal string to float number in C#.

As such, float specifies a 32-bit floating point value, the precision can be 7 digits. If your string with the decimal number is greater than 7 precision then use the double data type.

See the code below for learning how to convert a string with the decimal number to float by Parse method:

using System;



class string_to_float

{

    static void Main()

    {

        float Pos_flt_Str = float.Parse("39.55");

        float neg_flt_Str = float.Parse("-101.25");



        Console.WriteLine("Positive float number = " + Pos_flt_Str);

        Console.WriteLine("Negative float number = " + neg_flt_Str);





        Console.ReadLine();

    }

}

The output:

c# string-to-float

The example of using TryParse

The TryParse method is useful for conversion if there are chances of an incorrect string as a number. The Parse method can also be programmed, however, the TryParse has built-in capability by returning a Boolean as return value.

For example, you are taking the user input from a text box and there are chances that the entered number may contain spaces or characters other than valid numbers. In that case, if TryParse method is used, it will return false.

The simple usage of TryParse method is:

bool var1 = int.TryParse(string_number, out number)

See a simple example below to display the converted number by using the TryParse method:

using System;



class string_to_int_TryParse

{

    static void Main()

    {

        string str_conv = "101";

        int int_conv;

        bool flg_con = Int32.TryParse(str_conv, out int_conv);



        Console.WriteLine("Converted number by TryParse = " + int_conv);



        Console.ReadLine();

    }

})

As the string contains a valid number, so it is converted and its value is assigned to the int_conv variable.

What if a string is not a valid number?

Now, have a look at the code and output below if the string to be converted into number is a non-valid number:

using System;



class TryParse_false

{

    static void Main()

    {

        string str_num = "101A";

        int int_a;

        bool ret_val = Int32.TryParse(str_num, out int_a);



        if (ret_val)

        {

            Console.WriteLine("Converted number by TryParse = " + int_a);

        }

        else

        {

            Console.WriteLine("An invalid string!");

        }

        Console.ReadLine();

    }

}

You can see, I set the value of the string variable as 101A, which is an invalid number. Unlike the Parse method, this did not generate an error. Instead, it returned the false value that we dealt with in the if..else block.

The output of the above code should be:

An invalid string!

An example of string to int by Convert class

By using Convert class methods, you may convert a string to numbers. For a string to int conversion, use the Convert.ToInt32 method. For converting a string “number” to decimal, use the ToDecimal, ToDouble etc.

In the following example, a string is converted by Convert.ToInt32(String) to an integer number. Have a look:

using System;



class Convert_Class_example

{

    static void Main()

    {

        string str_convert = "1010";

        int int_converted;

        int_converted = Convert.ToInt32(str_convert);



        Console.WriteLine("Result after Convert method = " + int_converted);



        Console.ReadLine();

    }

}

The output:

Result after Convert method = 1010

Following numeric conversion methods are also available in the Convert class:

  • For short type : ToInt16(str)
  • For Integer : ToInt32(str)
  • For long type: ToInt64(str)

The example of string to float by Convert class

Similarly, you may use the ToSingle() method of the Convert class for converting a “decimal string” to float.

See the following example:

using System;



class Convert_Class_example

{

    static void Main()

    {

        string str_convert_flt = "555.5555";

        float flt_converted;

        flt_converted = Convert.ToSingle(str_convert_flt);



        Console.WriteLine("Float Result = " + flt_converted);



        Console.ReadLine();

    }

}

The result:

Float Result = 555.5555

For greater precision, use the ToDouble(str) method.