Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to parse "-1.#IND", etc using Double.Parse method

Tags:

c#

.net

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?

like image 589
etkarayel Avatar asked Feb 21 '14 13:02

etkarayel


2 Answers

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;
}
like image 124
D Stanley Avatar answered Oct 03 '22 21:10

D Stanley


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);
}
like image 34
Sinatr Avatar answered Oct 03 '22 19:10

Sinatr