Calculating compound interest with .NET and C#
October 9. 2012 0 Comments
- Posted in:
- Code
I spent some time looking for a simple compound interest calculation function in .NET today. I couldn't find anything usable, so I grabbed the source formula and reduced it to .NET.
Here's the formula:
A = P * (1 + r / n) ^ n * t A = final total amount P = principal amount r = interest rate (decimal) n = number of periods per year t = number of years
The C# code:
decimal CalculateTotalWithCompoundInterest(decimal principal, decimal interestRate, int compoundingPeriodsPerYear, double yearCount) { return principal * (decimal)Math.Pow((double)(1 + interestRate / compoundingPeriodsPerYear), compoundingPeriodsPerYear * yearCount); }
For example, you can calculate the total loan amount for $10,000.00 (principal and interest), compounded daily for 2 years like so:
decimal total = CalculateTotalWithCompoundInterest(10000m, 8.5m, 365, 2);