Sheil
Sheil

Reputation: 213

Reading double from console

How can I read double value for example 0.3 from Console? When I type something with .X like mentioned before 0.3 it throws Exception.

So far I've tried something like that:

Console.WriteLine("Type x: ");
double x = Convert.ToDouble(Console.ReadLine());

Upvotes: 0

Views: 6359

Answers (3)

Rufus L
Rufus L

Reputation: 37020

I would use TryParse:

Console.Write("Type x: ");
var input = Console.ReadLine();
double value;

while (!double.TryParse(input, NumberStyles.Any,
    CultureInfo.InvariantCulture, out value))
{
    Console.Write("{0} is not a double. Please try again: ");
    input = Console.ReadLine();
}

Console.WriteLine("Thank you! {0} is a double", value);

Upvotes: 0

Soner Gönül
Soner Gönül

Reputation: 98740

Convert.ToDouble(string) method uses Double.Parse with your CurrentCulture settings. Here how it's implemented;

public static double ToDouble(String value)
{
     if (value == null)
         return 0;
     return Double.Parse(value, CultureInfo.CurrentCulture);
}

And this Double.Parse implemented as;

public static double Parse(String s, IFormatProvider provider)
{
    return Parse(s, NumberStyles.Float| NumberStyles.AllowThousands, NumberFormatInfo.GetInstance(provider));
}

As you can see, this parsing operation will succeed only if your NumberStyles.Float| NumberStyles.AllowThousands matches with your CurrentCulture settings.

I strongly suspect your CurrentCulture's NumberFormatInfo.NumberDecimalSeparator property is not dot (.) And that's why your code throws FormatException.

You can 2 options; use a culture that have NumberDecimalSeparator as a . like InvariantCulture or .Clone your CurrentCulture and set it's NumberDecimalSeparator to ..

Console.WriteLine("Type x: ");
double x = DateTime.Parse(Console.ReadLine(), CultureInfo.InvariantCulture);

or

var culture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
culture.NumberFormat.NumberDecimalSeparator = ".";
Console.WriteLine("Type x: ");
double x = DateTime.Parse(Console.ReadLine(), culture);

Upvotes: 4

Giorgos Betsos
Giorgos Betsos

Reputation: 72165

Try this instead:

double x = double.Parse(Console.ReadLine(), NumberStyles.Any, CultureInfo.InvariantCulture);

Upvotes: 1

Related Questions