0

I am doing a project where I have to calculate year to date daily compound interest on transactions.Currently I am only getting the current balance with no interest. I believe my issue is with the foreach loop but I am not sure where I have made a mistake. It is going through the days but either there is no interest being applied or runningTotal is not carrying over properly.

                public IEnumerable<DateTime> EachDay(DateTime from, DateTime thru)
    {
        for (var day = from.Date; day.Date <= thru.Date; day = day.AddDays(1))
            yield return day;
    }

    public decimal PrincipalplusInterest()
    {
        DateTime startDate = new DateTime( DateTime.Now.Year, 1, 1);
        DateTime endDate = startDate.AddYears(1);
        int compoundingTimes = 12;

        TimeSpan duration = endDate - startDate;
        var numberOfDaysInYear = duration.Days;

        decimal runningTotal = 0;
        double interestRate = InterestRate;

        foreach (DateTime day in EachDay(startDate, endDate))
        {
            decimal sumOfAnyTransactionToday = Transactions.Where(x => x.TransactionDate == day).Sum(x => x.Amount);

            runningTotal = runningTotal + sumOfAnyTransactionToday;

            double timePeriod = 1 / numberOfDaysInYear;
            double rate = interestRate / compoundingTimes;
            double total = System.Convert.ToDouble(runningTotal);

            double principalAndInterest = total * Math.Pow((1 + rate), (compoundingTimes * timePeriod));
            runningTotal = System.Convert.ToDecimal(principalAndInterest);

        }
        return runningTotal;
    }


    [DisplayName("Year to Date Interest")]
    public decimal YrToDateInterest()
    {
        decimal interest = PrincipalplusInterest() - CurrentBalanceCalculation();
        return interest;
    }
A.Lawson
  • 1
  • 2
  • 1
    In addition to ChrisF's answer, its worth noting the difference between decimal and double - particularly since you're dealing with money. http://stackoverflow.com/questions/1165761/decimal-vs-double-which-one-should-i-use-and-when – JonLord Oct 08 '16 at 21:54

1 Answers1

0

You are doing integer arithmetic here:

double timePeriod = 1 / numberOfDaysInYear;

numberOfDaysInYear is an int, so dividing 1 by this value will always return 0.

Make the calculation floating point by making one of the values floating point:

double timePeriod = 1.0 / numberOfDaysInYear;

is probably the easiest solution.

Also if your transactions contain a time component then this statement will always return zero, unless you happen to have a transaction that occurred exactly at midnight.

Transactions.Where(x => x.TransactionDate == day).Sum(x => x.Amount);

To just get the date you need to do get the Date component of the DateTime object:

Transactions.Where(x => x.TransactionDate.Date == day).Sum(x => x.Amount);
ChrisF
  • 134,786
  • 31
  • 255
  • 325