Why doesn't C # TryParse handle NaN?
I have some common methods for parsing with overriding default values ββwhen reading in some old Fortran data. Sometimes the data has NaN (Not a number)
where the numeric value should be. I expected TryParse to see the string "NaN" and not parse. However, TryParse successfully parses and puts NaN
in for a numeric value. Is this the expected behavior? If this is expected, are there any other "getcha" values ββI should be looking for?
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;
}
UPDATE
I feel like it should be mentioned that this only happens for double, long and int does not return NaN value. See sample code below, Common .... code is simply formatted with Console.WriteLine, or stops to execute the console. See screenshot below for output.
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();
}
source to share
From MSDN :
The s parameter can contain NumberFormatInfo.PositiveInfinitySymbol , NumberFormatInfo.NegativeInfinitySymbol, or NumberFormatInfo.NaNSymbol for the vendor-specified culture.
There are three "special" values ββto look for. However, the last few words are key - depending on the current culture, you might see something other than "NaN"
!
source to share
Double.NaN is a valid double, so that's okay. There is also negative and positive infinity. Check here for other possible "special" values.
source to share