无法使用double.Parse解析字符串

4

我在将字符串解析为双精度浮点数时遇到了问题。我有一个StreamWriter从文本文件中读取行,文本文件包含以下行:

17-09-2012: (100,98)
17-09-2012: (50,57)

现在,我想使用括号中的值将它们相加并显示在文本框中。 我目前有以下内容:

int counter = 0;
double res = 0;
string line;

System.IO.StreamReader file = new System.IO.StreamReader("d:\\test.txt");
while ((line = file.ReadLine()) != null)
{
    string par = Regex.Match(line, @"\(([^)]*)\)").Value;
    double par2 = double.Parse(par);
    res += par2;

    counter++;
}
file.Close();
textBox1.Text = res.ToString();

然而,显然输入字符串格式不正确,这使我感到非常奇怪,因为正则表达式应该删除括号内以外的所有内容。我甚至通过在不先将它们相加的情况下将字符串写入文本框来检查它,并显示为“100,9850,57”。所以实际上,我不明白为什么不能将字符串转换为双精度浮点数。希望您能告诉我哪里做错了。

3
+1 for adding an SSCCE and showing what you've tried. +1 表示赞成,因为您加入了一个SSCCE并展示了您的尝试。 - S.L. Barth
2
我不确定你的编程语言是否支持逗号表示浮点数。 - gtgaxiola
我不认为这是事实,因为我已经制作了一个可以处理逗号分隔数字的计算器。当时我没有做任何特殊处理来实现这一点。 - Robin
你已输出字符串的内容了吗?你确定它只包含数字和逗号吗? - Brian Warshaw
@Brian Warshaw 是的,我确定。 - Robin
6个回答

2

你的“par”变量包含一个看起来像“(100,98)”的字符串,所以它无法解析。


我不明白它是如何做到的。当我将“par”作为纯文本输出时,它不包含任何括号。 - Robin
我发现我的代码中还有其他东西在删除括号。将正则表达式更改为仅输出数字后,它仍无法解析。 - Robin

1

将您的正则表达式更改为(?<=\()(([^)]*))(?=\))


0

你可以尝试使用基于 InvariantCulture 的方法

 var culture = CultureInfo.InvariantCulture;
 double result = double.Parse(par , culture);

0
你可以强制使用将,作为十进制分隔符的区域设置来解析double.Parse,例如:
CultureInfo culture = new CultureInfo("de-DE");
double d = double.Parse(par, culture);

无论如何,如果您希望您的程序也能在不同区域设置的计算机上运行,那么这是一个好主意。


当我输入“CurrentCulture”时,它显示找不到类型或命名空间。我需要键入“using.something;”才能使用它吗? - Robin
使用 System.Globalization; 但我犯了一个错误(应该使用 CultureInfo,而不是 CurrentCulture...) - Paolo Falabella
即使现在,它仍然无法接受输入。显然不是逗号的问题。 - Robin
你所说的“它不接受输入”是什么意思?它会抛出异常吗?如果是,它说了什么? - Paolo Falabella
它显示“输入字符串的格式不正确”,并指向以下行:“double par2 = double.Parse(par);” - Robin

0

将您的正则表达式设置为(?<=\()(([^)]*))(?=\))并使用此辅助程序应该解决您的问题:

        public static double ParseDouble(string input)
        {
            // unify string (no spaces, only . )
            string output = input.Trim().Replace(" ", "").Replace(",", ".");

            // split it on points
            string[] split = output.Split('.');

            if (split.Count() > 1)
            {
                // take all parts except last
                output = String.Join("", split.Take(split.Count() - 1).ToArray());

                // combine token parts with last part
                output = String.Format("{0}.{1}", output, split.Last());
            }

            // parse double invariant
            double d = Double.Parse(output, CultureInfo.InvariantCulture);
            return d;
        }

如何在我的代码中实现这个?我可以把它放在“while”括号里吗? - Robin
不,你必须将它放在同一个类中或者在一个新类的单独.cs文件中,比如“Helpers”之类的。 - Mihalis Bagos

0

我通过使用try catch让它工作:

string par = Regex.Match(line, @"(?<=\()(([^)]*))(?=\))").Value;
                try
                {
                    double par2 = double.Parse(par);
                    res += par2;
                }
                catch
                {
                }

谢谢大家的帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接