Skip to content

How to convert int to string

Drew Taylor

Asked Oct 2, 2006, 12:40 AM EDT9 answers
Share
LinkedInX

How do I convert an int to a string, for example if a variable  is declared as an int and it needs to take user input. I need to convert it so that the user can enter a value. Then I need to do some calulations on the value entered by the user. I know you have to user int 32 parse but I don't know how and where to put it

9 Answers

Know the answer? Post it. Somebody with the same question will find it here.

  • 0
    you can try this one.

    Code
    int num = 5;
    string str;
    str = num.ToString();
    0
  • 0

    It says The type or namespace num Could not be found. What does this mean?

    0
  • 0
    you can try this code: Convert.ToString(//the variable that holds the int value);
    0
  • 0
    int a=10; string str=Convert.Tostring(a); Response.Write(str);
    0
  • 0

    use any of the below mentioned methods:

    int a = 10;
    Convert.ToString(a);

    or

    int a = 10;

    string str = a.ToString();

    0
  • 0
    Use the TryParse method to convert a user input string into a number.  If you use any other method and the input is non-numeric, it will throw an exception.  TryParse is new with VS 2005.  If the input is non-numeric, it will simply return 0.  It will work with any type, not just integers.

    string sa; int ia;
    Console.Write("Enter a number:  ");
    sa = Console.ReadLine();
    Int32.TryParse(sa, out ia);
    0
  • 0
    try using CStr function in C#.net
    0
  • 0

    Thanks for you replies everyone. I know how to convert data types, but I don't know how to use tryparse.

    0
  • 0
    I just showed you exactly how to use TryParse.  Here it is again.  You can use it to convert from a string to just about any type.  First you get the string value.  Then you use the TryParse method as follows (spelled out for you step by step):

    Type to convert to
    dot
    TryParse
    (
    the string variable
    ,
    out
    the variable of the type to convert to
    )
    ;


    Example for converting a string named sa to an integer named ia, supposing that the user input is placed in TextBox1:

    string sa; int ia;
    sa = TextBox1.Text
    Int32.TryParse(sa, out ia);
     

    Is that clear enough for you?

    Also remember that if you want to process the number mathematically and display the result in another textbox, you need to convert the number back into a string again.

    string snum; int inum;
    snum = Convert.ToString(inum);
    TextBox2.Text = snum
    0