How do I convert a string to Int32?

  • Thread starter Thread starter Jeff Reed
  • Start date Start date
J

Jeff Reed

Doing something like this (cast) doesn't work.

Y.value = (Int32)stringvariable;

I get this message:
Cannot convert type 'string' to 'int'

Any idea how I can convert string to Int32?

thxs
Jeff Reed
 
Jeff said:
Any idea how I can convert string to Int32?

int.Parse(string)

There's also the Convert class or double.TryParse. I like TryParse
because it won't throw an exception.

--
There are 10 kinds of people. Those who understand binary and those who
don't.

http://code.acadx.com
(Pull the pin to reply)
 
Hi to you,

TryParse is a little bit slower. If you're sure that your string is a
numeric (You can use RegularExpression) then i suggest you Int32.Parse or
int.Parse (same thing)
 
Frank Oquendo said:
There's also the Convert class or double.TryParse.

You might still get an error converting the double to an int. It would be fairly easy to write a TryParse function for int, or
create a function that does the conversion and returns 0 if there is an error (or a default value).
 
Michael said:
You might still get an error converting the double to an int. It
would be fairly easy to write a TryParse function for int, or create
a function that does the conversion and returns 0 if there is an
error (or a default value).

TryParse enver throws an exeption. Instead it will return false and set
the out parameter to 0. You can also specify NumberStyles.Integer as an
argument. That will help avoid any casting errors. I use TryParse all
the time and have never had a problem with using to convert strings to
ints.

--
There are 10 kinds of people. Those who understand binary and those who
don't.

http://code.acadx.com
(Pull the pin to reply)
 
I didn't know about the second parameter. However, if you create your own function you don't require a cast or to type the second
param. Most the time in my app I just do Gen.ToInt32(x) where Gen is a class I use for common functions.
 
Michael said:
I didn't know about the second parameter.

There's more than that as well. Another parameter is NumberFormatInfo
object. I normally pass
System.Globalization.CultureInfo.CurrentCulture.NumberFormat. Between
that and the NumberStyles parameter, you can parse all manner of strings
such as 10000, 10,000 or even $10,000 all with a single line of code.
However, if you create your
own function you don't require a cast or to type the second param.

Yep, a simple wrapper does come in handy if you don't want to perform a
cast from double to int.

--
There are 10 kinds of people. Those who understand binary and those who
don't.

http://code.acadx.com
(Pull the pin to reply)
 
Back
Top