Search code examples
c#bitconverter

Overflow exception in C# for converting float number to decimal


I get an overflow exception when Convert.ToDecimal(float number here) is called. I'm reading from a byte string and hoping to convert the byte array to a decimal number.

byte[] hexbyte = {45, 6, 7, 29};
float myFloat = BitConverter.ToSingle(hexbyte, 0);

//Make sure the float can be converted to decimal
if (!float.IsNaN(myFloat) ||
    !float.IsInfinity(myFloat) ||
    myFloat < (float)decimal.MaxValue ||
    myFloat > (float)decimal.MinValue)
{
    try {
        myFloatD = Convert.ToDecimal(myFloat);
    }
    catch (Exception ex)
    {
        Debugger.Log(0, "1", ex.ToString());
        return 0;
    }
}
else
    return 0;

myFloat = (float)Math.Round(myFloatD, 2); // 1 indicates the decimal places

Even when I put constrains to check whether the float is too large/too small/to infinity for the conversion, the code still ends up at the catch exception...


Solution

  • You're using or operators where you should be using and operators. It is possible for any float which is NaN, infinite, > decimal.MaxValue or < decimal.MinValue to pass your if criteria, as long as it is not all of those things at the same time.

    Here's what you need to ensure:

    myFloat < (float)decimal.MaxValue && myFloat > (float)decimal.MinValue
    

    Here's what you're actually ensuring:

    myFloat < (float)decimal.MaxValue || myFloat > (float)decimal.MinValue
    

    The latter is always true for any given float, even ones that are outside the valid bounds of the decimal type.