To convert a string to a number in C#, you can use the built-in methods provided by the Convert class:
Use the Convert.ToInt32 method to convert a string to an integer:
string str = "123";
int number = Convert.ToInt32(str);
Use the Convert.ToDouble method to convert a string to a double:
string str = "123.45";
double number = Convert.ToDouble(str);
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.
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
Asked: 2023-07-01 23:04:03 +0000
Seen: 10 times
Last updated: Jul 01 '23