-1

I have a csv reader class that reads a bunch of .csv files Save the content of several csv files into a searchable array C#

In these files I have values with decimals (saved as strings) that I want to prase from a string to a double:

public double GetVal(string filename, int row, int column)
        {
            filename = filename + ".csv";
            try
            {
                string returnstring = _dictionary[filename][row][column];
                double returnval = double.Parse(returnstring);
                return returnval;
            }
            catch //if the value cannot be converted to a double, for instance if it is a header
            {
                return Double.NaN;
            }
        }

This works very well on my own computer with English languages settings (Windows 10). However when I try to prase a returnstring like 1810.5 I get an error when using Swedish languages settings on other machines. In the Swedish settings we use , instead of . as a marker for decimals. Is there any way to make C# understand that . is always used for decimals no matter the Windows language settings?

Sean
  • 60,939
  • 11
  • 97
  • 136
KGB91
  • 630
  • 2
  • 6
  • 24

2 Answers2

4

You need to define the culture you want to use to parse the string. Try this:

double.Parse(returnString, CultureInfo.InvariantCulture)

This uses the double.Parse overload that takes a CultureInfo as second argument and passes CultureInfo.InvariantCulture which uses a . as decimal point.

René Vogt
  • 43,056
  • 14
  • 77
  • 99
  • Seems to work if I include `using System.Globalization;`, but need to test it on my Swedish system tomorrow. – KGB91 Mar 16 '20 at 17:05
2

Use the double.Parse(String, IFormatProvider) overload, and pass an appropriate CultureInfo object for the second parameter. In your case, you probably want:

double.Parse(returnstring, CultureInfo.InvariantCulture);
Joe Sewell
  • 6,067
  • 1
  • 21
  • 34