0

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?

Matthew Layton
  • 39,871
  • 52
  • 185
  • 313
  • You know that the max size of a decimal is smaller than the max size of a float? https://stackoverflow.com/questions/21951834/float-double-and-decimal-max-value-vs-size – gunr2171 Aug 16 '22 at 22:25

2 Answers2

3

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
isakgo_
  • 750
  • 4
  • 15
1

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://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/floating-point-numeric-types

Juan Erenas
  • 220
  • 1
  • 9