How to convert Console.ReadLine() to double in simple calculator ? C# Problem with exception

浪子不回头ぞ 提交于 2021-02-17 05:20:30

问题


I used double.Parse and Convert.ToDouble and got the same error

System.FormatException: Input string was not in a correct format.

When I write in console 10.2 or any other double number.

I learnt from a tutorial and I followed it step by step but I have no idea how to solve this.

Also I am using Visual Studio.

Console.WriteLine("Enter a number: ");
double num1 = double.Parse(Console.ReadLine());

Console.Write("Enter operator: ");
string op = Console.ReadLine();

Console.WriteLine("Enter a number: ");
double num2 = double.Parse(Console.ReadLine());

if (op == "+")
{
    Console.Write(num1 + num2);
}
else if (op == "-")
{
    Console.WriteLine(num1 - num2);
}
else if (op == "/")
{
    Console.WriteLine(num1 / num2);
}
else if (op == "*")
{
    Console.WriteLine(num1 * num2);
}
else
{
    Console.WriteLine("Invalid Operator");
}

回答1:


The problem might be your culutral setting. Some countries uses a . others uses a ,

try:

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

or set the separator like:

var culture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
culture.NumberFormat.NumberDecimalSeparator = ".";
double num2 = DateTime.Parse(Console.ReadLine(), culture);


来源:https://stackoverflow.com/questions/60372540/how-to-convert-console-readline-to-double-in-simple-calculator-c-sharp-probl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!