Ask Your Question
3

How to convert a string in C# to a number?

asked 2023-07-01 23:04:03 +0000

nofretete gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-07-01 23:29:02 +0000

plato gravatar image

To convert a string to a number in C#, you can use the built-in methods provided by the Convert class:

  1. Use the Convert.ToInt32 method to convert a string to an integer:

    string str = "123";
    int number = Convert.ToInt32(str);
    
  2. Use the Convert.ToDouble method to convert a string to a double:

    string str = "123.45";
    double number = Convert.ToDouble(str);
    
  3. Use the int.TryParse or double.TryParse methods to convert a string to an integer or double, respectively. These methods return a boolean value indicating whether the conversion was successful or not:

    string str = "123";
    int number;
    if (int.TryParse(str, out number))
    {
       // Conversion successful
    }
    
    string str = "123.45";
    double number;
    if (double.TryParse(str, out number))
    {
       // Conversion successful
    }
    

Note that if the string cannot be converted to a number, an exception will be thrown in the first two methods. The TryParse methods are safer since they will not throw an exception and instead return a boolean value indicating the success of the conversion.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-01 23:04:03 +0000

Seen: 10 times

Last updated: Jul 01 '23