C# converting to double returns infinity

Thick_propheT picture Thick_propheT · Jul 1, 2012 · Viewed 10.7k times · Source

I have a method:

public void StoreNumberInSmallestType(ValueType number)
{
    if (numberTypes == null)
        numberTypes = new List<Type>() { typeof(sbyte), typeof(short), typeof(int), typeof(long), typeof(float), typeof(double) };

    foreach (Type t in numberTypes)
    {
        try
        {
            var converter = TypeDescriptor.GetConverter(t);
            value = converter.ConvertTo(number, t);

            Type = value.GetType();

            return;
        }

        catch (OverflowException) { }
    }
}

The method is inside a class where the variable value is defined as dynamic.

When used like this:

StoreNumberInSmallestType(Math.Pow(200, 100));

value ends up being Infinity. If I step through the process, I find that the value of number is not Infinity, but is the result expressed in scientific notation. Something bad is happening whenever number gets converted and stored inside value. Does anybody know why number holds the correct value, but value does not?

EDIT:

Here is a complete code sample:

Main:

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Class1 c1 = new Class1();
            c1.StoreNumberInSmallestType(Math.Pow(200, 100));
        }
    }
}

Class:

namespace ConsoleApplication1
{
    public class Class1
    {
        List<Type> numberTypes;
        dynamic value;
        public Type Type { get; set; }

        public void StoreNumberInSmallestType(ValueType number)
        {
            if (numberTypes == null)
                numberTypes = new List<Type>() { typeof(sbyte), typeof(short), typeof(int), typeof(long), typeof(float), typeof(double) };

            foreach (Type t in numberTypes)
            {
                try
                {
                    var converter = TypeDescriptor.GetConverter(t);
                    value = converter.ConvertTo(number, t);

                    Type = value.GetType();

                    return;
                }

                catch (OverflowException) { }
            }
        }
    }
}

Answer

Mark Hall picture Mark Hall · Jul 1, 2012

It happens when you run a conversion on your number with the Single Type which has a max value of 3.40282347E+38 and the value of nunber is 1.2676506002282294E+230 so you are exceeding the Single Value Type. Once you make it to the Double Type it will have 1.2676506002282294E+230 in value.

From above link:

If the magnitude of the result of a floating-point operation is too large for the destination format, the result of the operation is PositiveInfinity or NegativeInfinity, as appropriate for the sign of the result.