The write-up will explain the process of converting a string to double in C#.
Change an Input String to “Double” in C#
In C#, “Double” is basically a floating point number with 15 digits. We use double to store values of decimal numbers. There are three methods in C# for converting the string to double:
Method 1: Using ToDouble()
Through the “ToDouble()” function we can convert a string to double. For this purpose, simply initialize a string in code and then use the “Convert.ToDouble()” function and put the name of that string inside the brackets of this function and then print the required output. It will show the results by converting the string to double. For example:
public class Doublestring
{
public static void Main(string[] args)
{
String a = "103.23456712985990653256";
Console.WriteLine(Convert.ToDouble(a));
}
}
In this code:
- First, we use the namespace library named “System”.
- Then, declare the “Doublestring” class.
- Next, use the “main()” method.
- Inside the “main()” method, we initialize a string “a”.
- After that, we convert that string using the “Convert.ToDouble()” method and print the result on the console.
Here is the output of the above-described code:
Method 2: Using Double.Parse()
The “Double.Parse()” method is also used to convert a string into double format. For example:
public class Doublestring
{
public static void Main(string[] args)
{
String a = "103.23456712985990653256";
Double b=Double.Parse(a);
Console.WriteLine(b);
}
}
Here:
- We call the “Double.Parse()” method and save results into the double type “b” variable.
- Then, show the resultant value on the console by using the “Console.WriterLine()” method.
Output
As you can see, the output is the same as the output of the “ToDouble()” method.
Method 3: Using Double.TryParse()
The “Double.TryParse()” method is a boolean function that is utilized for checking whether the string is a valid double or not. It takes two arguments, such as the string and the type double. For example:
public class Doublestring
{
public static void Main(string[] args)
{
String a = "103.23456712985990653256";
Double b;
Console.WriteLine(Double.TryParse(a,out b));
}
}
In this code:
- We have a class “Doublestring” in which we have a “main()” method.
- In the “main()” method, we declare and initialize the string as “a” and a double as “b”.
- Then, we check whether we can convert that string to a double or not.
Output
Note: In “Double.TryParse()” the “out” keyword is used to reference the argument.
Conclusion
In C#, the string can be converted to doubles by using “ToDouble()”, “Double.Parse()” and “Double.TryParse()” methods. These methods use the input strings and display the doubled value as output. That’s all about converting a string to double in C#.