user3492977 user3492977 - 4 months ago 8
C# Question

Converting a string like "09335887170" to an integer

How can I convert a string like "09335887170" to an integer? Here is what I have tried:

string a = "09335887170";
int myInt;
bool isValid = int.TryParse(a, out myInt); // it returns false in this case

if (isValid)
{
int plusOne = myInt + 1;
MessageBox.Show(plusOne.ToString());
}

MessageBox.Show(a);
int stringToInt = Convert.ToInt32("09335887170"); // it returns nothing with no error
MessageBox.Show((stringToInt + 1).ToString());

int test = int.Parse(a); //it has type convertion error
MessageBox.Show((test + 1).ToString());

Answer

The maximum value of a Int32 (or only int) is 2,147,483,647 you need a UInt64 or Int64 or Long

string a = "09335887170";
Int64 myInt;
bool isValid = Int64.TryParse(a, out myInt);
if (isValid)
{
    int plusOne = myInt + 1;
    MessageBox.Show(plusOne.ToString());
}
Comments