Link to home
Start Free TrialLog in
Avatar of elsia
elsia

asked on

converting string to int

how do i convert numbers in string format to int? i tried:

     String strtab;
     int tab id;
     tabid = Integer.parseInt(strtab); and
     tabid = (int)strtab;

but both return an error:
CS0246: The type or namespace name 'Integer' could not be found (are you missing a using directive or an assembly reference?) and
CS0030: Cannot convert type 'string' to 'int'

How do i convert?

Avatar of esteban_felipe
esteban_felipe

Hi elsia,
Try
tabid = Int322.parse(strtab)
or
tabid = Convert.toInt32(strtab);

Esteban Felipe
www.estebanf.com
Avatar of elsia

ASKER

Hi esteban,

I still cant get it working.. it returns me an error saying:
System.FormatException: Input string was not in a correct format.
ASKER CERTIFIED SOLUTION
Avatar of esteban_felipe
esteban_felipe

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of elsia

ASKER

thanks for the pointer :)
Could you show some sample values of the variable - strtab that you are trying to convert?

Gajendra
Avatar of elsia

ASKER

my strtab is actually an URL with numbers which i truncated but did not pass it back to strtab.. therefore, my strtab actually contains alphabets
JUst so anyone looking knows, you can do this:

try{
   myInt = Convert.toInt32("mys_invalid_string");
}catch(Exception){
   // give user a beating
}
int myInt = int.Parse("123");
just do this:

public int convertStringToInt(string strSource)
{
  try
 {
   return int.Parse(strSource);
 }
catch
{
return null;
}

}

you can use it to check the real int :))
Please do like this :
int32.Parse(strSource)

to make sure NO characters in the strSource
conversion from string will work only if the entire string is a valid number. if you have any character or non-numeric character embeded in your string you will get an error.

Gajendra
       Dim n As Integer
       
Try

            n = Convert.ToInt32(txtbInput.Text)

 

            txtbInput.Text = ""

            Try

                rtbOutput.Text = factorial(n).ToString + vbCrLf

            Catch ovException As OverflowException

                MsgBox("Overflow!")

            End Try

        Catch fmtException As FormatException

            MsgBox("The input shoul be an integer number!")

        End Try

 

Now, test the input with any inputs and see what will happen.

Vikram Lashkari
I had to create a parseInt style method for a project I was working on:

private int ParseInt(string str)
{
      char[] chars = str.ToCharArray();
      string numeric = "";

      for(int i=0; i<chars.Length; i++)
      {
            if(CharIsNumeric(chars[i]))
            {
                  numeric += Convert.ToString(chars[i]);
            }
      }

      if(numeric != "")
            return Convert.ToInt32(numeric);
      else
            return 0;
}

private bool CharIsNumeric(char c)
{
      int charCode = Convert.ToInt32(c);
      if(charCode > 47 && charCode < 58)
            return true;
      else
            return false;
}

This will pull any numbers out of a string, concat them, and retrun the Int value of them.

Tim
try{

   myintNum = Convert.toInt32("mys_invalid_string");
}catch(Exception){
   // check the exception here ...
}

conversion from string will work only if the entire string is a valid number.

so you either have to check for each character in the string and check its the ASCII 48-57 range and then write your own procedure to ensure that.

-messageman
if your going to make a isnumeric (CharIsNumeric) like function don't forget about decimal numbers
Here is a little function that can check if a number is numeric before converting

public static bool IsNumeric(string stringValue)
{
      Regex _isNumber = new Regex(@"^\d+$");
      Match m = _isNumber.Match(stringValue);
      return m.Success;
}

Avatar of elsia

ASKER

thanks all for the tips, advice and suggestions even though the points has been given out. Nice to be part of the forum.. Well done, Expert Exchange!
Nice work taranki, really useful.
Hello leeseifer,
Your function won't compile since its return type is 'int' and int is a "value type" and can't hold null as a value.

Opher.
Hello taranki,
You could compact your function to this:

private int ParseInt(string str)
{
     System.Text.StringBuilder numeric = new System.Text.StringBuilder("0");

     for(int i=0; i<str.Length; i++)
     {
          if(Char.IsDigit(str[i]))
          {
               numeric.Append(str[i]);
          }
     }

     try
     {
          return int.Parse(numeric.ToString());
     }
     catch
     { // overflow!
          return -1;
      }
}

Opher.
you may try these:
1. int tableID = Int32.parse(strtab);
OR
2. int tableID = Convert.ToInt32(strtab);

:-D
One point regarding a post above. Try catch blocks should never be used to provide functionality, in this case, if you want to try to parse and integer, the int.tryParse method should really be used as below
int int1;
 
if(int.TryParse(strTab, out int1))
{
    //Parse was successful
    return int1;
}
else
{
    //Parse was not successful
    reutrn null;
}

Open in new window