用小数 C# 双重解析

Double parse with decimals C#

我有一个 csv reader class 可以读取一堆 .csv 文件

在这些文件中,我想要将 prasestring 变为 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;
            }
        }

这在我自己的计算机上使用英语设置时效果很好 (Windows 10)。但是,当我尝试 prase1810.5 这样的 returnstring 时,在其他机器上使用瑞典语设置时出现错误。在瑞典设置中,我们使用 , 而不是 . 作为小数点标记。有什么方法可以让 C# 理解 . 始终用于小数,无论 Windows 语言设置如何?

您需要定义要用于解析字符串的区域性。试试这个:

double.Parse(returnString, CultureInfo.InvariantCulture)

这使用 double.Parse overloadCultureInfo 作为第二个参数并传递使用 . 作为小数点的 CultureInfo.InvariantCulture

使用 double.Parse(String, IFormatProvider) 重载,并为第二个参数传递适当的 CultureInfo 对象。在你的情况下,你可能想要:

double.Parse(returnstring, CultureInfo.InvariantCulture);