[英]System.Format.FormatException when trying double.Parse()
My program throws a System.FormatException: "The entrystring has the wrong format."
我的程序抛出
System.FormatException: "The entrystring has the wrong format."
whenever I am trying run this code: 每当我尝试运行此代码时:
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;
}
I have also tried to run it with Convert.ToDouble(elem)
and Encodings with ascii and utf_8. 我也尝试过使用
Convert.ToDouble(elem)
和带有ascii和utf_8的Encodings来运行它。 None of these worked. 这些都不起作用。
To understand my code: 要了解我的代码:
I call the function from another function and the CoordString
argument looks like this: 90 10 1000
So they are all Integers, but I need them as double. 我从另一个函数调用该函数,并且
CoordString
参数看起来像这样: 90 10 1000
所以它们都是Integer,但是我需要将它们作为double。 (I tried Int32.Parse()
and then convert to double, here it crashes on the Int32.Parse()
part) (我尝试过
Int32.Parse()
,然后将其转换为double,在这里它在Int32.Parse()
部分崩溃了)
My code should get the CoordString ( "90 10 1000"
) and split it into single strings ( ["90", "10", "1000"]
). 我的代码应获取CoordString(
"90 10 1000"
)并将其拆分为单个字符串( ["90", "10", "1000"]
)。 The Console.WriteLine(elem)
prints the correct numbers, no letters, just numbers as string. Console.WriteLine(elem)
打印正确的数字,不打印字母,仅显示数字作为字符串。
Any idea why / how to fix it? 知道为什么/如何解决? Nothing other questions suggested worked so far.
到目前为止,没有其他建议的问题起作用。
EDIT: 编辑:
The weird thing is, printing elem
does work well. 奇怪的是,打印
elem
效果很好。 But the Exception Window shows me this: 但是异常窗口向我显示了这一点:
b 0 double
elem "" string
// The class name here
You probably have a double space somewhere that's causing the problem. 您可能在某个地方存在双倍空格,从而导致了问题。 Try specifying
StringSplitOptions.RemoveEmptyEntries
: 尝试指定
StringSplitOptions.RemoveEmptyEntries
:
string[] cArrStr = CoordString(' ', StringSplitOptions.RemoveEmptyEntries)
instead of 代替
string[] cArrStr = CoordString.Split(' ');
Also, you should use Double.TryParse
and not Convert.ToDouble
, since Double.TryParse
will only return false when it can't convert, while Convert.ToDouble
will throw an exception: 另外,您应该使用
Double.TryParse
而不是Convert.ToDouble
,因为Double.TryParse
仅在无法转换时将返回false,而Convert.ToDouble
将引发异常:
So use this: 所以使用这个:
double b;
if(Double.TryParse(elem, out d))
{
// value is a double
}
instead of 代替
double b = Convert.ToDouble(elem);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.