5

Trying to use System.Double.Parse(string) method for strings such as "-1.#IND" and "INF" representing special values results in a FormatException.

Is there any built-in .NET framework support to parse these?

etkarayel
  • 373
  • 1
  • 2
  • 9

2 Answers2

6

No, the only non-numeric values double.Parse recognizes are the string values returned by double.Nan.ToString(), double.PositiveInfinity.ToString(), and double.NegativeInfinity.ToString() (dependent on Culture).

In your case I would just use a switch:

double dblValue;
switch strValue
{
   case "-1.#IND":
      dblValue = double.Nan;
      break;
   case "INF":
      dblValue = double.Infinity;
      break;
   //... other casess
   default:
      dblValue = double.Parse(strValue);
      break;
}
D Stanley
  • 149,601
  • 11
  • 178
  • 240
2

NaN and other values are parsed in the specified culture (or neutral, if no culture is specified). You can play with those here if you want.

If you have to parse something more special, then just

public double MyParse(string text)
{
    if(text == "blablabla")
        return double.NaN;
    if(text.Contains("blablabla")) ...
    if(text.StartsWith(...
    return double.Parse(text);
}
Sinatr
  • 20,892
  • 15
  • 90
  • 319