tags:

views:

96

answers:

2

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.

Can anyone help me with it please?

+2  A: 

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.

Jon Skeet
Thanks Jon, I am building a calculation engine and needed access to Math.Pow which only uses doubles. I convert back to decimal for display purposes.Any pointers would be great.
Burt
@Burt - if you are simply displaying it, why not display a string representation?
Oded
@Burt: What sort of power are you using? It's *relatively* rare to use non-integer powers for `decimal` IME. For integer powers you could just loop and multiply :)
Jon Skeet
@Jon you are right it is always an integer, but would this error still not occur if I am hitting the upper boundary of the decimal?
Burt
@Burt: Yes, you've still fundamentally got a problem here - but I'm suggesting that aside from that, staying within the world of `decimal` would be a good idea (or use `double` to start with). Basically make a choice and stick to it :)
Jon Skeet
@Jon OK, it is looking like it will have to be double. A couple of questions how best to display doubles is it string.format(...)?What does double map to in SQL server?
Burt
@Burt: The best way to display a double will depend on the context. Do you wish to show the exact value? Use scientific notation etc? I'm reluctant to comment on the SQL side of things, as it would be so easy to be subtly wrong and it's not an area I have much experience with.
Jon Skeet
@Jon I have a feeling I should have had your book in with me today. It will be non-scientific notation, and I am assuming I will need string.format for this.
Burt
@Burt: You don't necessarily need to call `string.Format` - just `x.ToString("some format specifier")` may be simpler. Not that my book would have helped here, I'm afraid.
Jon Skeet
+2  A: 

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.

Oded