简体   繁体   中英

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());

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 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);

尝试以下方法:

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM