C# converting to double returns infinity
-
18-06-2021 - |
Question
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) { }
}
}
}
}
Solution
You don't get infinity for the double conversion, but for the float conversion.
There you get Infinity and no exception and then your code returns before you get to the double conversion.
OTHER TIPS
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.
Overflow conditions cause Infinity; You can check for this with either of these:
- MSDN: double.IsPositiveInfinity
- MSDN: double.IsNegativeInfinity
The float conversion is causing you to exceed the limitations of your data type.