在读取一些旧的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;
}
Run Code Online (Sandbox Code Playgroud)
UPDATE
我觉得应该提到,这只发生在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();
}
Run Code Online (Sandbox Code Playgroud)
Jac*_*all 10
来自MSDN:
该小号参数可以包含NumberFormatInfo.PositiveInfinitySymbol,NumberFormatInfo.NegativeInfinitySymbol,或NumberFormatInfo.NaNSymbol用于通过提供商指示的培养.
有三个"特殊"值需要注意.然而,最后几个字是关键 - 取决于当前的文化,你可能会看到除了以外的东西"NaN"!
| 归档时间: |
|
| 查看次数: |
1348 次 |
| 最近记录: |