Search code examples
c#floating-pointdecimalprecisionconverters

What is the minimum decimal which can be converted to float and then back to decimal?


var t = (decimal)((float)decimal.MinValue)

fails with error CS0031: Constant value '-7.922816E+28' cannot be converted to a 'decimal', but why?

decimal.MinValue is -79228162514264337593543950335m. It successfully converts to float as -79228160000000000000000000000f wichh is larger than decimal.MinValue:

(float)decimal.MinValue > decimal.MinValue

Why this value can't be converted? I understand it's something about the significand and the exponent but what exactly happen? And which is minimum decimal which can be converted to float and then back to decimal in C#?


Solution

  • You are not printing the full precision of the float, so you cannot see the value that is causing it to fail.

    If you change the code as follows:

    var decMin = (float)decimal.MinValue;
    Console.WriteLine(decMin.ToString("R")); // "-7.9228163E+28"
    
    // Next line throws System.OverflowException: Value was either too large or too small for a Decimal.
    var dec = (decimal)decMin; 
    

    The value of decMin is displayed as -7.9228163E+28. To make this easier to compare, let's rewrite that without the exponent and compare it to decimal.MinValue:

    decMin           = -79_228_163_000_000_000_000_000_000_000
    decimal.MinValue = -79_228_162_514_264_337_593_543_950_335
    

    Now you can see that decMin is MORE NEGATIVE than decimal.MinValue - which explains why it fails to convert.