简体   繁体   中英

Compound Interest Calculation

I have this C# code which calculate compound interest plus principal amount every year.

static void CompoundInterest(double principal, double interestRate, double years, double annualCompound)
    {
        var total = 0.0;
        for (int t = 1; t < years + 1; t++)
        {
            total = principal * Math.Pow((1 + interestRate / annualCompound),
                                     (annualCompound * t));
            Console.Write("Your Total for Year {0} "
                        + "is {1}. \n", t, total);
        }
    }

When I tested it with

 CompoundInterest(1000, 0.05, 3, 12);

and the output is

Your Total for Year 1 is 1051.161897881733.
Your Total for Year 2 is 1104.941335558327.
Your Total for Year 3 is 1161.4722313334678.

How should I round it accurately? Another question is Math.Pow uses double but in financial calculation, we need decimal . How do I fix this? Convert into decimal after Math.Pow ?

You can convert a double to a decimal directly if you'd like

decimal decimalTotal = (decimal)total;

As for rounding, there is a built-in function, Math.Round, that takes a variety of number formats. It has a overload to specify how many decimal points you want.

decimal roundedDecimal = Math.Round(decimalTotal, 2);

I made some test by rounding first and converting to decimal and by converting to decimal and then rounding afterword. Both gave the same results.

But from the logic point of view, I would convert first than rounding after words. This way I will have better control of testing what is converted and what is rounded.

For converting there are different answers, but I found this method Convert.ToDecimal is supported by all .net frameworks and cores.

ex. decimal value = Convert.ToDecimal(double_value);

And then you decimal.Round , which some one has asked and got answer here Why does .NET use banker's rounding as default?

Just in case reference to Floating-point numeric types .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM