Mohanapriya R Mohanapriya R
Updated date Jul 25, 2024
In this article, we will learn the ins and outs of converting strings to doubles in C#.
  • 6.5k
  • 0
  • 0

String-to-Double Conversion Methods:

Double.Parse() Method:

The Double.Parse() method is used to convert strings to doubles in C#. It takes a string as input and returns its double equivalent. However, if the string is not a valid representation of a double, a FormatException will be thrown.

string inputString = "3.14";
double result = Double.Parse(inputString);
Console.WriteLine(result);

Output:

3.14

Double.TryParse() Method:

The Double.TryParse() method is a safer alternative to Double.Parse() as it does not throw an exception if the conversion fails. Instead, it returns a boolean indicating whether the conversion was successful or not.

string inputString = "ABC";
if (Double.TryParse(inputString, out double result))
{
    Console.WriteLine(result);
}
else
{
    Console.WriteLine("Invalid input");
}

Output:

Invalid input

Convert.ToDouble() Method:

The Convert.ToDouble() method is another option for string-to-double conversion. It can handle null strings and returns 0 if the conversion fails.

string inputString = "42.75";
double result = Convert.ToDouble(inputString);
Console.WriteLine(result);

Output:

42.75

Let's use these methods with a simple program that takes user input and converts it to a double:

using System;

class Program
{
    static void Main()
    {
        Console.Write("Enter a number: ");
        string userInput = Console.ReadLine();

        if (Double.TryParse(userInput, out double result))
        {
            Console.WriteLine($"Double value: {result}");
        }
        else
        {
            Console.WriteLine("Invalid input. Please enter a valid number.");
        }
    }
}

Output:

Enter a number: 25.5
Double value: 25.5

Comments (0)

There are no comments. Be the first to comment!!!