简体   繁体   English

从控制台读取双

[英]Reading double from console

How can I read double value for example 0.3 from Console? 如何从控制台读取double值,例如0.3? When I type something with .X like mentioned before 0.3 it throws Exception. 当我使用0.3之前提到的.X键入内容时,它将引发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. Convert.ToDouble (字符串)方法将Double.ParseCurrentCulture设置一起使用。 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; 这个Double.Parse实现为;

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 ,此解析操作才会成功NumberStyles.Float| NumberStyles.AllowThousands NumberStyles.Float| NumberStyles.AllowThousands matches with your CurrentCulture settings. NumberStyles.Float| NumberStyles.AllowThousands与您的CurrentCulture设置匹配。

I strongly suspect your CurrentCulture 's NumberFormatInfo.NumberDecimalSeparator property is not dot ( . ) And that's why your code throws FormatException . 我强烈怀疑您CurrentCultureNumberFormatInfo.NumberDecimalSeparator属性不是点( . ),这就是为什么您的代码引发FormatException的原因。

You can 2 options; 您可以选择2个选项; use a culture that have NumberDecimalSeparator as a . 使用具有NumberDecimalSeparator的区域性. like InvariantCulture or .Clone your CurrentCulture and set it's NumberDecimalSeparator to . InvariantCulture.Clone您的CurrentCulture并将其NumberDecimalSeparator设置为. .

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: 我会使用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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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