Wednesday, May 16, 2007

How do I cast a string to an int, float, double, etc?

How do I cast a string to an int, float, double, etc?

You can use the Convert class or the Parse method of the built-in type you are casting to. i.e.

string myStr = "123";
int myParsedInt = Int32.Parse(myStr);
int myConvertedInt = Convert.ToInt32(myStr);

This example uses the int type, but you can also use the same techniques for any of the other integral or floating point types.

No comments: