-2

I need a program that takes two inputs from the user and perform a calculation. Those inputs need to be double datatype.

The problem I'm facing is that: the program receives a decimal value with dot separator, but when converting it to double, it loses the decimal value. For example, input from the user is 2.5, but when converting it becomes 25.

When the user type 2,5 it is correctly converting it to 2.5

Here's my code example:

Console.WriteLine("Var1: ");
string? v1 = Console.ReadLine();
Console.WriteLine("Var2: ");
string? v2 = Console.ReadLine();

double v1Double = Double.Parse(v1);
double v2Double = Double.Parse(v2);
Console.WriteLine($"Var1: {v1Double}");
Console.WriteLine($"Var2: {v2Double}");

Console.WriteLine($"Multiplication: {v1Double * v2Double}");

Here's what I'm getting when with dot separator:

enter image description here

Here's what I'm gettig when comma separator:

enter image description here

Can anyone help me how to address this problem?

  • Your system regional settings are set to use `,` as the decimal separator. Either change that, or set the format explicitly in code – Charlieface Aug 28 '22 at 23:50

1 Answers1

1

You could use NumberFormatInfo for this problem like so:

NumberFormatInfo provider = new NumberFormatInfo();
provider.NumberDecimalSeparator = ".";
provider.NumberGroupSeparator = ",";
double doubleVal = Convert.ToDouble(YOUR_STRING, provider);
MrFabio_25
  • 478
  • 5
  • 9