C# How to Convert String to Double with Examples
In C#, convert a string to a double using
double.Parse(stringValue) or safely with double.TryParse(stringValue, out double result) to avoid errors.Examples
Input"123.45"
Output123.45
Input"-98.76"
Output-98.76
Input"abc"
OutputConversion failed (TryParse returns false)
How to Think About It
To convert a string to a double, first consider if the string is always a valid number. If yes, use
double.Parse. If not, use double.TryParse to check and convert safely without errors.Algorithm
1
Get the input string.2
Try to convert the string to a double using a safe method.3
If conversion succeeds, return the double value.4
If conversion fails, handle the error or return a default value.Code
csharp
using System; class Program { static void Main() { string input = "123.45"; if (double.TryParse(input, out double result)) { Console.WriteLine(result); } else { Console.WriteLine("Conversion failed"); } } }
Output
123.45
Dry Run
Let's trace converting "123.45" using TryParse.
1
Input string
input = "123.45"
2
Try to convert
double.TryParse("123.45", out result) returns true, result = 123.45
3
Output result
Print 123.45
| Step | Input | TryParse Result | Output |
|---|---|---|---|
| 1 | "123.45" | true | 123.45 |
Why This Works
Step 1: Parsing the string
double.Parse converts a valid numeric string directly to a double but throws an error if invalid.
Step 2: Safe conversion
double.TryParse attempts conversion and returns true or false without throwing errors, making it safer.
Step 3: Using the result
If TryParse returns true, the converted double is stored in the output variable for use.
Alternative Approaches
double.Parse
csharp
using System; class Program { static void Main() { string input = "123.45"; double result = double.Parse(input); Console.WriteLine(result); } }
Throws an exception if the string is not a valid number, so use only when sure input is valid.
Convert.ToDouble
csharp
using System; class Program { static void Main() { string input = "123.45"; double result = Convert.ToDouble(input); Console.WriteLine(result); } }
Also converts string to double but throws exception on invalid input; similar to Parse.
Complexity: O(n) time, O(1) space
Time Complexity
Conversion scans the string once, so time depends linearly on string length.
Space Complexity
Uses constant extra space for the output double variable.
Which Approach is Fastest?
double.Parse and double.TryParse have similar speed; TryParse is safer for unknown input.
| Approach | Time | Space | Best For |
|---|---|---|---|
| double.Parse | O(n) | O(1) | Known valid strings |
| double.TryParse | O(n) | O(1) | Unknown or user input strings |
| Convert.ToDouble | O(n) | O(1) | Similar to Parse, with null handling |
Use
double.TryParse to safely convert strings without risking exceptions.Trying to convert invalid strings with
double.Parse without error handling causes runtime exceptions.