[ACCEPTED]-Convert "1.79769313486232E+308" to double without OverflowException?-double
Unfortunately this value is greater than 11 double.MaxValue
, hence the exception.
As codekaizen suggests, you 10 could hard-code a test for the string. A 9 better (IMO) alternative if you're the one 8 producing the string in the first place is to use 7 the "r" format specifier. Then the string 6 you produce will be "1.7976931348623157E+308" instead, which 5 then parses correctly:
string s = double.MaxValue.ToString("r");
double d = double.Parse(s); // No exception
Obviously that's no 4 help if you don't have control over the 3 data - but then you should understand you're 2 likely to be losing data already in that 1 case.
The problem is likely due to the fact that 11 Double.MaxValue
was converted to a string, and when the 10 string is output, not all the digits are 9 output, instead it is rounded. Parsing this 8 value overflows the double.
Using Double.TryParse
and subsequently 7 checking equality on the string "1.79769313486232E+308" in 6 case of failure and substituting Double.MaxValue
should 5 be a quick workaround, if you need to keep 4 the string the way it is.
EDIT: Of course, if 3 you don't need to keep the string the way 2 it is, use the Round Trip format specifier to produce the string in 1 the first place, as Jon describes in his answer.
You may try double.Parse()
or double.TryParse()
rather than Convert.ToDouble()
, but I'm not 10 certain you'll get better results. Incidentally, the 9 string that you provide is equal to double.MaxValue
, which 8 is (of course) the maximum value that can 7 be contained in a double, so that's likely 6 where your error is coming from. Floating-point 5 numeric types are finicky, so I would assume 4 that some sort of rounding is taking place 3 and pushing it outside the bounds of the 2 type.
You could also try the decimal
data type. You 1 may have better luck there.
Here is what I came up with. Thanks Jon 1 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;
}
Demonstrates the issue and a solution:
var s = double.MaxValue.ToString();
double d;
if (!double.TryParse(s, out d)) {
d = s.Equals(double.MaxValue) ? double.MaxValue : double.MinValue;
}
0
Here a more generic implementation which 2 representing different formatting and cultures 1 and is more tolerant:
#region MatchDoubleMinMaxValuesRegex
/// <summary>
/// This regex matches strings which represents either a <see cref="double.MinValue"/> or a <see cref="double.MaxValue"/>.
/// If it is a <see cref="double.MinValue"/> then the group "isNegative" will be matched as <see cref="Group.Success"/>.
/// </summary>
private static readonly Regex MatchDoubleMinMaxValuesRegex = new Regex(
@"
^
(?>(?<isNegative>-)|\+?)
1
(?>[,.]?)
79769313486232
(?>
[eE]\+308|
0{294}(?>[,.]|$)
)
",
RegexOptions.Compiled | RegexOptions.IgnorePatternWhitespace
);
#endregion
/// <summary>
/// Converts the string representation of a number in a specified culture-specific format to its double-precision floating-point number equivalent.
/// <para>This implementation is more tolerant compared to the native double.Parse implementation:
/// strings representing <see cref="double.MinValue"/> and <see cref="double.MaxValue"/> can be parsed without <see cref="OverflowException"/>.</para>
/// </summary>
/// <param name="s">A string that contains a number to convert.</param>
/// <param name="cultureInfo">For some type conversions optional culture information that shall be used to parse the value.
/// If not specified, then the Current Culture will be used.</param>
/// <param name="numberStyles">For some type conversions optional number style configuration that shall be used to parse the value.
/// If not specified, then the default will be used.</param>
/// <returns>A double-precision floating-point number that is equivalent to the numeric value or symbol specified in <paramref name="s"/>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="s"/> is <c>null</c>.</exception>
/// <exception cref="FormatException"><paramref name="s"/> does not represent a number in a valid format.</exception>
/// <exception cref="OverflowException"><paramref name="s"/> represents a number that is less than <see cref="double.MinValue"/> or greater than <see cref="double.MaxValue"/>.</exception>
public static double ParseDoubleEx(string s, CultureInfo cultureInfo = null, NumberStyles? numberStyles = null)
{
// Try parse
double tempValue;
bool parseSuccess = (numberStyles != null)
? double.TryParse(s, numberStyles.Value, cultureInfo, out tempValue)
: double.TryParse(s, NumberStyles.Any, cultureInfo, out tempValue);
// If parsing failed, check for Min or Max Value (by pattern)
if (parseSuccess == false)
{
Match match = MatchDoubleMinMaxValuesRegex.Match(s);
if (match.Success == true)
tempValue = (match.Groups["isNegative"].Success == false)
? double.MaxValue
: double.MinValue;
else
throw new OverflowException("A double-precision floating-point number that is equivalent to the numeric value or symbol specified in s.");
}
return tempValue;
}
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.