-2

I want to ask a user to input a number in a string type (because that's the only way in C#) and then convert it into a double type.

private static string InputDouble(double prompt)
{
    Console.WriteLine("{0:s}: ", prompt);
    return Convert.ToDouble(Console.ReadLine());
}

I hope anyone has a solution for this.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Rammah
  • 27
  • 1
  • 6

2 Answers2

1

You can use Double's TryParse method:

public Double? StringToDouble(String input){
    if(Double.TryParse(input, out Double d)) {
        Console.WriteLine("The double value is {0}", d);
        return d;
    }
    else{
       Console.WriteLine("The input string was not in correct format");
   }
   return null;
}

The advantage of the TryParse method over the Parse method is that in case the input is not in correct format, it does not throw any exception and rather it returns a boolean indicating whether the value has been successfully parsed or not.

Transcendent
  • 5,598
  • 4
  • 24
  • 47
0

Use Double.Parse:

private static double InputDouble(double prompt)
{
    Console.WriteLine("{0:s}: ", prompt);
    return Double.Parse(Console.ReadLine());
}
Nick
  • 4,787
  • 2
  • 18
  • 24