Matthew Layton
Matthew Layton

Reputation: 42260

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?

Upvotes: 0

Views: 464

Answers (2)

Juan Erenas
Juan Erenas

Reputation: 320

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

Upvotes: 1

na_sacc
na_sacc

Reputation: 868

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

Upvotes: 3

Related Questions