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

Time:08-17

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?

CodePudding user response:

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

CodePudding user response:

As IsakGo pointed out, the decimal is narrower than float or double. This is because decimal has much higher precision than either float or double do. This is why decimal is used most for financial applications instead of float or double.

Because of the precision it has, decimal has a narrower range. You can read more about it here: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/floating-point-numeric-types

  • Related