The behavior you're experiencing is due to the fact that the Convert.ToDouble(string)
method uses the double.Parse(string)
method internally. When you pass a string representing a value greater than Double.MaxValue
, the double.Parse(string)
method returns Double.PositiveInfinity
instead of throwing an OverflowException
.
Here's the modified code to demonstrate this:
using System;
public class Example
{
public static void Main()
{
string s_num = "1.7976931348623157E+400"; // > Double.MaxValue
double num = Convert.ToDouble(s_num); // Returns Double.PositiveInfinity, not OverflowException
Console.WriteLine(num.ToString()); // Output: ∞
if (double.IsInfinity(num))
{
Console.WriteLine("The value is greater than Double.MaxValue");
}
}
}
To handle cases when the parsed value is greater than Double.MaxValue
, you can check for double.IsInfinity(num)
and handle it accordingly.