how do i convert to double in closed c?

When converting an unknown string to a double, the best bet is the double.TryParse method, because it does two things:

  1. Returns a bool indicating whether or not the input was successfully parsed to a double
  2. Sets an out parameter to the parsed value, or 0 if unsuccessful.

This is better than Convert.ToDouble because that method will just throw an exception if it fails.

Here’s a good way to get a double from the user in a Console application, where we use the result of double.TryParse as a while condition, and we loop while it’s not true (basically we wait for the user to enter a valid number before doing any calculations):

Console.Write("Please enter a radius: ");
string input = Console.ReadLine();

double radius;

while (!double.TryParse(input, out radius))
    Console.ForegroundColor = ConsoleColor.Red;
    Console.WriteLine($"{input} is not a valid number. Please try again.\n");

    Console.Write("Please enter a radius: ");
    input = Console.ReadLine();

double area = Math.PI * (radius * radius);

Console.WriteLine($"The area of a circle with radius {radius} is: {area}");

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top