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

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

Rate This
  • Comments 19

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.

[Author: Joe Mayo]

Leave a Comment
  • Please add 4 and 6 and type the answer here:
  • Post

  • Is there any difference between the two methods? Is one just a wrapper for the other? Does one have more functionality or is one faster?
  • The Convert methods call the Parse methods. For just converting a string, there is logically no difference. However, if you look at the docs for both methods, there are different overloads for each method that may make it attractive to select one method over the other. For example, Parse allows you to specify a NumberStyles parameter and Convert has an overload that allows you to specify the base type to use when converting the string.
  • Both, Parse and ToInt32 throw if they can't convert.

    What makes me wonder is that only the double data type supports a Double.TryParse routine.

    Would be cool to habe such a "TryParse" for all integral types. Any reason why this is not the case currently?
  • I think too that all the int, float, etc... must have a TryParse() method, because the try-catch struct is too slow to be useful.

    But I think that ALL the value type must have it too. What about converting a string to a DateTime?
  • There's one difference between Int32.Parse and Convert.ToInt32 - the latter returns 0 if it is passed null, whereas the former throws an exception.

    I believe there will be TryParse methods in Whidbey, but I haven't checked.

    As for try-catch being too slow to be useful - it depends on how many you're doing. I can throw and catch many thousands of exceptions per second on my box - far more than I need to if I'm validating user input, but not necessarily enough if I'm running through a huge file with millions of invalid values. A simple hard coded check can weed out the vast majority of invalid values quickly, followed by using try/catch. I believe that's usually the best approach if performance is a problem.

    As for converting a string to a DateTime - I tend to use DateTime.ParseExact for maximum control.
  • Here's the BCL Team Blog announcement of support for TryParse on all the base datatypes in Whidbey:
  • Speaking of Whidbey I almost love this method:

    object Convert.ChangeType( object o, Type t )

    very usefull in the following scenario:

    public T ConvertFromString(string s){
    return (T)Convert.ChangeType(s, typeof(T));
  • Finally, my turn to be a smart-ass... :)

    I just love the title of this post... doesn't anybody bother to remember the difference between casting and converting anymore? You can't CAST a string to an int or any other numeric type!!! But you can CONVERT a string to an int or another numeric type, assuming the string is actually a number.

    Correct me if I'm wrong, but casting is when you change the type of an object reference to another type in that object's inheritance hierarchy, while converting is actually transforming a value into another value of a different type that may or may not be part of the same inheritance hierarchy!
  • No, casting doesn't necessarily do that. Casting can also invoke explicit (or implicit) conversion operators - for instance from SqlString to String.

    In general though, I feel your pain - it would be nice if people would stop assuming that they should be able to cast in order to do conversions.
  • PingBack from

  • PingBack from

  • MSDN article: "How to: Determine Whether a String Represents a Numeric Value (C# Programming Guide)".

    In short, this is what Microsoft suggests:

    int i = 0;

    string s = "108";

    bool result = int.TryParse(s, out i); //i now = 108

    After the above code executes,:

    If the string can be successfully converted, the variable "i" will contain it value and the variable "result" will equal true. The above article has more examples.

  • Thank u Mr.Dave Moss, I got the Result

  • Here is a post on this

  • Obrigado por contribuir para a comunidade de desenvolvedores.

    Eu compartilho informações parecidas por meio do artigo entitulado

    [Como Tratar Exceção ao Converter String para Número Inteiro (Int32) com C#], disponível em

    Thanks for contributing to the developer community. I share similar information through the article titled [How to Handle Exception to Convert String to Integer (Int32) with C #], or in portuguese, [Como Tratar Exceção ao Converter String para Número Inteiro (Int32) com C#] available at

Page 1 of 2 (19 items) 12