0

I'm a complete beginner, trying to learn.

The code below compiles just fine, without any exceptions on my Mac version of Visual Studio Community.

However, in the PC version, "measurements[i] = Convert.ToDouble(Console.ReadLine());" results in a "System.FormatException error"

I would like to understand, the difference in how the mac version handles the exceptions i suppose?

Both the mac and PC projects are .NET 3.1 console applications.

        double[] measurements = new double[3];

        for(int i = 0; i < measurements.Length; i++)
        {
            Console.Write("Input a decimal number: ");

            measurements[i] = Convert.ToDouble(Console.ReadLine());
        }
Samalens
  • 3
  • 2
  • 1
    Are you talking about exception during runtime or compile time? Runtime is when exception is thrown when you run your application, compile time is when you build your application. – Fabio Dec 05 '20 at 17:42
  • What is the specific string you enter for `Console.ReadLine()`? `Convert.ToDouble()` does localized parsing by default, probably you have different numeric localization on each computer. See: [Decimal Point ignored in Convert.ToDouble](https://stackoverflow.com/q/37461888/3744182). – dbc Dec 05 '20 at 17:47

1 Answers1

0

Based on exception, I would guess that different machines (mac and windows) have different culture configurations (decimal point comma vs period or others).

To have culture agnostic behaviour I would suggest to parse given string to double with forced invariant culture (period as decimal separator)

var measurements = new double[3];

for(int i = 0; i < measurements.Length; i++)
{
    Console.Write("Input a decimal number: ");
    var value = Console.ReadLine();  // 42.99

    measurements[i] = double.Parse(value, CultureInfo.InvariantCulture);
}
Fabio
  • 31,528
  • 4
  • 33
  • 72