Burt
Burt

Reputation: 7758

Value was either too large or too small for a Decimal

I have the following piece of code:

double shortfall = GetSomeNumber(); //3.3588548831176006E+29

if (shortfall > 0)
{
  returnValue = Convert.ToDecimal(shortfall);
}

That generates the above error.

Upvotes: 31

Views: 74032

Answers (3)

Wielder
Wielder

Reputation: 156

If you badly need a decimal variable. Then you have to add 1 more condition

if (shortfall > 0)
{
    if (shortfall.ToString().Contains("E"))
        return Convert.ToDecimal($"{shortfall:E8}".Substring(0, 10));
    else if (shortfall.ToString() != "NaN")
        return Convert.ToDecimal(AnnualVal);
    else
        return 0;
}

Upvotes: 0

Oded
Oded

Reputation: 498972

It means that the value returned cannot be converted to decimal as it is too large.

Decimal values can be between positive 79,228,162,514,264,337,593,543,950,335 to negative 79,228,162,514,264,337,593,543,950,335 - see MSDN.

Double can handle much larger numbers - negative 1.79769313486232e308 to positive 1.79769313486232e308. These will not all be convertible to Decimal.

Upvotes: 15

Jon Skeet
Jon Skeet

Reputation: 1500245

Well, it's fairly self-explanatory.

decimal.MaxValue is 79,228,162,514,264,337,593,543,950,335 - your number is bigger than this.

Although decimal has a finer precision than double, double has a bigger range - it can handle very, very large and very, very small numbers.

Now, if you could tell us what you're really trying to do, we could try to help find a solution... it's rarely a good idea to mix double and decimal, to be honest.

Upvotes: 38

Related Questions