Search code examples
c#floating-pointdecimal-point

Float to Decimal Conversion in C#


int i = 1;        // -2,147,483,648 to 2,147,483,647
float f = 2.1f;      // -3.402823e38 to 3.402823e38
long l = 3;       // -922337203685477508 to 922337203685477507
double dbl = 4.5;   // -1.79769313486232e308 to 1.79769313486232e308
decimal dec = 5.2m;  // -79228162514264337593543950335 to 79228162514264337593543950335

dec = i;     // No error
dec = l;     // No error

dec = f;    // Compiler error
dec = dbl;  // Compiler error

f = (float)dec; // No error (May loss precision) ok

**dec = (decimal)dbl;** // No error  why it requires ?  

Why the above code requires Explicit Cast. Range of float/Double > Decimal ?


Solution

  • Because it isn't just about precision; you need to think about range too - and frankly 1.79769313486232e308 is really, really large (as in > 300 digits to the left of the decimal place). Your assertion "Even Range of decimal > float or double" is incorrect.

    var dbl = double.MaxValue;
    var dec = (decimal) dbl; // BOOM!
    

    The range of a double is larger than the range of a decimal.

    Also, you might need to consider double.NaN, double.PositiveInfinity and double.NegativeInfinity.