3

I'm wondering why the book we're using's example is using a mix of decimals and doubles with a cast to decimal when necessary. Would it not be simpler to just make everything decimals and avoid the casts altogether?

Here's the main chunk of code that I'm curious about.

decimal amount;
decimal principal = 1000;
double rate = 0.05;

for (int year = 1; year <= 10; year++)
{
    amount = principal * ((decimal) Math.Pow(1.0 + rate, year));
}

Are there any performance or accuracy issues that I'm overlooking?

InsanityOnABun
  • 5,973
  • 5
  • 21
  • 25

3 Answers3

6

There's no overload of Math.Pow that works with decimal - exponentiation on reals is inherently inaccurate, so it wouldn't make all that much sense for such an overload to exist.

Now since the only place where rate is used is in calculating the compound factor (the Pow call), it makes sense for it to be declared double - higher precision wouldn't help if it's going to just be 'cast away'.

The rest of the variables represent money, which is the use-case for decimal (that's why the suffix for decimal literals is M). One could imagine another computation where commmision of $2.10 were added to amount - we don't want such calculations to become inaccurate all for the sake of type-consistency in one pesky (inaccurate) compound-interest calculation.

Hence the inconsistency.

Ani
  • 111,048
  • 26
  • 262
  • 307
  • Ah, so it doesn't. I understand the main differences between `decimal` and `double`, and that's actually why I asked - we're already working with decimals in that equation, so the performance gain between the two is sort of moot. Thanks. – InsanityOnABun Jan 26 '12 at 17:31
2

Decimal has a smaller range, but is more accurate than double. Decimal is what you should use to represent money in .Net. In the example you gave, amount and principal are monetary values. Rate is not. Thus, they are using the correct data types.

Here is the MSDN on Decimal: MSDN Decimal

John Kraft
  • 6,811
  • 4
  • 37
  • 53
0

You should read this topic

What it boils down to is: decimal is used for money/when you need precision in calculations, whereas double is more suited for scientific calculation because it performs better.

Community
  • 1
  • 1
Louis Kottmann
  • 16,268
  • 4
  • 64
  • 88