Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert "1.79769313486232E+308" to double without OverflowException?

Tags:

c#

.net

double

I have this string "1.79769313486232E+308" and am trying to convert it to a .NET numeric value (double?) but am getting the below exception. I am using Convert.ToDouble(). What is the proper way to do this conversion?

OverflowException: Value was either too large or too small for a Double

like image 930
Eric Schoonover Avatar asked Apr 20 '09 04:04

Eric Schoonover


4 Answers

Unfortunately this value is greater than double.MaxValue, hence the exception.

As codekaizen suggests, you could hard-code a test for the string. A better (IMO) alternative if you're the one producing the string in the first place is to use the "r" format specifier. Then the string you produce will be "1.7976931348623157E+308" instead, which then parses correctly:

string s = double.MaxValue.ToString("r");
double d = double.Parse(s); // No exception

Obviously that's no help if you don't have control over the data - but then you should understand you're likely to be losing data already in that case.

like image 91
Jon Skeet Avatar answered Oct 20 '22 17:10

Jon Skeet


The problem is likely due to the fact that Double.MaxValue was converted to a string, and when the string is output, not all the digits are output, instead it is rounded. Parsing this value overflows the double.

Using Double.TryParse and subsequently checking equality on the string "1.79769313486232E+308" in case of failure and substituting Double.MaxValue should be a quick workaround, if you need to keep the string the way it is.

EDIT: Of course, if you don't need to keep the string the way it is, use the Round Trip format specifier to produce the string in the first place, as Jon describes in his answer.

like image 43
codekaizen Avatar answered Oct 20 '22 15:10

codekaizen


You may try double.Parse() or double.TryParse() rather than Convert.ToDouble(), but I'm not certain you'll get better results. Incidentally, the string that you provide is equal to double.MaxValue, which is (of course) the maximum value that can be contained in a double, so that's likely where your error is coming from. Floating-point numeric types are finicky, so I would assume that some sort of rounding is taking place and pushing it outside the bounds of the type.

You could also try the decimal data type. You may have better luck there.

like image 30
Adam Robinson Avatar answered Oct 20 '22 16:10

Adam Robinson


Here is what I came up with. Thanks Jon Skeet and codekaizen.

private double convertToDouble(string str)
{
    double dbl;

    if (double.TryParse(str, out dbl))
        return dbl;

    if (str == "1.79769313486232E+308")
        return double.MaxValue;

    return double.MinValue;
}
like image 40
Eric Schoonover Avatar answered Oct 20 '22 15:10

Eric Schoonover