在读取一些旧的Fortran数据时,我有一些常用的解析默认值覆盖的方法。有时候数据有NaN (Not a number)
,其中应该有一个数值。我预计TryParse会看到字符串“NaN”并且无法解析。但是,TryParse成功解析并将NaN
放入数值。这是预期的行为吗?如果这是预期的,那么我应该寻找其他任何“陷阱”值吗?
public static double GetDoubleFromString(string s, double defaultOnFailure = 0)
{
//Must be here due to TryParse returning NaN to d and result is set to true below
if (s.Contains("NaN"))
{
log.Warn(string.Format("String contained NaN, returning defaultOnFailure {0} string was {1}", defaultOnFailure, s));
return defaultOnFailure;
}
var d = defaultOnFailure;
if (!double.TryParse(s.Trim(), out d))
{
log.Warn(string.Format("Failed to parse double from string returning defaultOnFailure {0} string was {1}", defaultOnFailure, s));
}
return d;
}
更新
我觉得应该提到,这只发生在double,long和int不会返回NaN值。请参阅下面的示例代码,Common ....代码只是格式化的Console.WriteLine或停止执行控制台。请参阅下面的截图以获取输出。
public static void NanTestMain()
{
Common.WriteBlankWithTitle("Test parse NaN");
string s = "NaN";
Common.WriteBlankWithTitle("NaN to Int");
int i;
var intSuccess = int.TryParse(s, out i);
Console.WriteLine(string.Format("Int parse of {0} parse = {1}", i, intSuccess));
Common.WriteBlankWithTitle("NaN to Double");
double d;
var doubleSuccess = double.TryParse(s, out d);
Console.WriteLine(string.Format("Double parse of {0} parse = {1}", d, doubleSuccess));
Common.WriteBlankWithTitle("NaN to Long");
long l;
var longSuccess = long.TryParse(s, out l);
Console.WriteLine(string.Format("Long parse of {0} parse = {1}", l, longSuccess));
Common.Pause();
}
答案 0 :(得分:10)
来自MSDN:
s 参数可以包含NumberFormatInfo.PositiveInfinitySymbol,NumberFormatInfo.NegativeInfinitySymbol或NumberFormatInfo.NaNSymbol,用于提供商指定的文化。
需要注意三个“特殊”值。但是,最后几个字是关键 - 根据当前的文化,您可能会看到"NaN"
以外的其他内容!
答案 1 :(得分:3)
Double.NaN是double的有效值,所以这是正常的。 还有消极和正无穷大。检查here是否有其他可能的“特殊”值。