【问题标题】:System.Format.FormatException when trying double.Parse()尝试 double.Parse() 时出现 System.Format.FormatException
【发布时间】:2018-01-06 01:19:07
【问题描述】:

每当我尝试运行此代码时,我的程序都会抛出 System.FormatException: "The entrystring has the wrong format."

public double[] ReturnCoordsFromString(string CoordString)
    {
        string[] cArrStr = CoordString.Split(' ');

        List<double> NumList = new List<double>();

        foreach (string elem in cArrStr)
        {
            Console.WriteLine(elem);
            double b = Convert.ToDouble(elem);   // <= Error is here
            NumList.Add(b);
        }
        double[] retN = NumList.ToArray<double>();

        return retN;
    }

我还尝试使用Convert.ToDouble(elem) 和使用 ascii 和 utf_8 的编码来运行它。这些都不起作用。

要理解我的代码:

我从另一个函数调用该函数,CoordString 参数如下所示: 90 10 1000 所以它们都是整数,但我需要它们作为双精度数。 (我尝试了Int32.Parse(),然后转换为double,这里它在Int32.Parse() 部分崩溃)

我的代码应该获取 CoordString ("90 10 1000") 并将其拆分为单个字符串 (["90", "10", "1000"])。 Console.WriteLine(elem) 打印正确的数字,没有字母,只是数字作为字符串。

知道为什么/如何解决它吗?到目前为止,没有其他建议的问题有效。

编辑:

奇怪的是,打印elem 效果很好。但是异常窗口向我显示了这一点:

b        0         double
elem     ""        string
// The class name here

【问题讨论】:

  • elem的值是多少??
  • elem 始终是来自CoordString.Split(' ') 的数组中的每个单独的字符串。总是将数字作为字符串,所以首先是90,然后是10,然后是1000
  • 我只是试试你的代码,它工作得很好。你确定输入字符串看起来像这样"90 10 1000"吗?
  • Convert.ToDouble 当你给它一个空字符串时抛出那个异常,你显然会这样做。抛出异常时CoordString 是什么。
  • 打印每个变量,它给了我这个:0 0 200 // This is CoordString0 // First Element0 // Second Element200 // Last element

标签: c# string parsing type-conversion double


【解决方案1】:

您可能有一个双倍空格导致问题。尝试指定StringSplitOptions.RemoveEmptyEntries

string[] cArrStr = CoordString(' ', StringSplitOptions.RemoveEmptyEntries)

而不是

string[] cArrStr = CoordString.Split(' ');

另外,您应该使用Double.TryParse 而不是Convert.ToDouble,因为Double.TryParse 只会在无法转换时返回false,而Convert.ToDouble 会抛出异常:

所以用这个:

double b;
if(Double.TryParse(elem, out d))
{
    // value is a double
}

而不是

double b = Convert.ToDouble(elem); 

【讨论】:

    猜你喜欢
    • 2020-05-10
    • 2015-11-16
    • 1970-01-01
    • 1970-01-01
    • 2017-10-17
    • 2016-02-05
    • 2020-05-12
    • 2019-06-15
    • 2020-04-22
    相关资源
    最近更新 更多