0

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");
}
LopDev
  • 823
  • 10
  • 26
MrToxity
  • 393
  • 1
  • 4
  • 8

2 Answers2

0

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);
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Julian
  • 886
  • 10
  • 21
  • Truth. I have never used "," in any language only "." Ehh ... I tried with "," and it works normally. God, how much time wasted :(( feels bad haha, thank you for your time and total senseless post...damn... -.- – MrToxity Feb 24 '20 at 09:22
  • Bonus ask: Is there a lot of difference caused by this? – MrToxity Feb 24 '20 at 09:28
  • Best you look https://learn.microsoft.com/en-us/dotnet/api/system.globalization.cultureinfo?view=netframework-4.8 if you want to know more – Julian Feb 24 '20 at 09:55
  • Also worth mentioning the Turkish "i", where calling ToUpper() doesn't return "I" - and ToLower() on "I" doesn't return "i". See, e.g. https://stackoverflow.com/q/3550213/1364007 – Wai Ha Lee Feb 24 '20 at 18:29
0

missing Line in WriteLine in lines 4 and 11

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

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

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

if (op == "+")
{
    Console.WriteLine(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");
}

this is fixed version as op has the broken version posted