Home > Net >  Converting decimal number in C#
Converting decimal number in C#

Time:10-14

My program runs fine when I enter a Integer number in the terminal, but when I try to enter a decimal number I get the following error message:

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

I can`t find the error. Can someone help me?

Here is the code:

Console.Write("Enter a number: ");

double num1 = Convert.ToDouble(Console.ReadLine());

Console.Write("Enter another number: ");

double num2 = Convert.ToDouble(Console.ReadLine());


Console.WriteLine(num1   num2);

Console.ReadLine();

I am using this input:

Enter a number: 3 
New number: 2.1 

By using an decimal number as input I get the error message. But if I for example use

Enter a number: 3 
New number: 2 

My program runs fine.

CodePudding user response:

Watch out for the globalization settings on your system and application. The problem could be the decimal separator you use. You can find the one that the application use with

    CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator

I solved on my programs just replacing the right decimal separator with the correct one in use by the program (yes, programs can have different culture).

CodePudding user response:

I use Parse or TryParse with replacement comma char , comma to dot . char and with System.Globalization.CultureInfo.InvariantCulture to take care about delimiter symbol. You can do the same:

string input = "1,23"; // If "1.23" - works too
double value1 = double.Parse(input.Replace(",", "."), 
                             System.Globalization.CultureInfo.InvariantCulture);
// or
double.TryParse(input.Replace(",", "."), 
                System.Globalization.NumberStyles.Any,
                System.Globalization.CultureInfo.InvariantCulture, 
                out double value2);

// Both gives output (for me):
// value1: 1,23
// value2: 1,23
  • Related