Convert.ToDouble(String) does not throw an overflow exception when max_value is exceeded

d'ARIENZO SAMUELE 20 Reputation points
2023-03-23T13:50:28.57+00:00

I use .NET 8.0 on vscode. In documentation (for .NET 8.0) of Convert.ToDouble(String) there is OverFlow Exception when Double.MaxValue is exceeded, but when I convert a string that represents a value>Double.MaxValue, it doesn't throw an exception, but give me a double with particular value.

using System;

public class Example
{
   public static void Main()
   {
     string? s_num = "1.7976931348623157E+400"; //>Double.MaxValue
     double num = Convert.ToDouble(s_num); //i'm expecting an Overflow Exception
     Console.WriteLine(num.ToString()); //output: 8
   }
}

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,784 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,821 questions
{count} votes

Accepted answer
  1. Sedat SALMAN 13,735 Reputation points
    2023-03-23T20:26:43.1433333+00:00

    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.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.