Convert string to int (not working for some strings)

I want to convert string to int but some time is not working.

Here is my code:

public static int ToInt(String pStr)
{
     return Convert.ToInt32(Microsoft.VisualBasic.Conversion.Val(pStr));
}

Int i = ToInt("F0005");

Output is 0 - it works fine.

But when I pass in a value like this

Int i = ToInt("E0305");

Then I get an error "Out-of-range exception".

I have a mix of values, some are int and some are strings; I want to pass each and every value in loop and convert it to int, but when I pass this value then I get an error.


If you just want to skip invalid string value, it is better to use TryParse instead of returning 0 (which might be valid value). At your calling code it should look like this:

string val = "F0005";
if (int.TryParse(val, out int i) {
   // parse success. you can use i here
}
else {
   // parse failed. 
}

If you really want it to be 0, this should work

string val = "F0005";
int i = int.TryParse(val, out int x) ? x : 0;

You can do it in C# alone without VB.NET library

public static int ToInt(string pStr)
{
     return int.Parse(pstr);
}

Noted that this will throw exception if pStr is not a valid integer string. In your case, it might also throw exception if the value is too big, which you might need long instead to hold bigger numbers.

public static long ToInt64(string pStr)
{
     return long.Parse(pstr);
}

Also, I just noticed that you are trying to parse "E0305" which is not really a valid format (as far as I know). The closest one is "1E305", which means 1 with 305 zeroes afterward. If you need to parse an integer that big, you might need BigInteger

public static BigInteger ToBigInteger(string pStr)
{
     return BigInteger.Parse(pstr, System.Globalization.NumberStyles.AllowExponent);
}

The System.Globalization.NumberStyles.AllowExponent part is there to allow parsing the number in exponent representation.