Search code examples
c#floating-pointieee-754

Why can't float/double MinValue/MaxValue fit inside a decimal?


Consider the following code:

float value = float.MinValue;
decimal dec = (decimal) value;

Unhandled exception. System.OverflowException: Value was either too large or too small for a Decimal.

The same applies for float.MinValue, float.MaxValue, double.MinValue, and double.MaxValue.

If float is 32-bit and double is 64-bit, why don't their min/max values fit inside a decimal which is 128-bit?


Solution

  • The reason is that deciaml is narrower than float or double.

    // decimal.MaxValue
    79228162514264337593543950335
    
    // decimal.MinValue
    -79228162514264337593543950335
    
    // float.MaxValue
    3.402823E+38
    
    // float.MinValue
    -3.402823E+38
    
    // double.MaxValue
    1.79769313486232E+308
    
    // double.MinValue
    -1.79769313486232E+308