Calculating the interest on savings account

It was long time since I wrote here last time. I’m coming back today with interesting and not so simple problem of your savings account and how interest is calculated for the money you put in.

Assumption is that every month you should get monthly interest worked out on the money from savings account. With this task we want to be penny perfect. So we can’t loose any money during the calculation. Also for simplicity account can be open only for fixed amount of years. As for example I use one year as it’s simple and later we’ll see how to handle situation when money is stored for many years.

At first you can think you need list of numbers. But is it really what you have to calculate? List used every month for crediting your main account is just representation. IMO all what you need here are three numbers. Monthly interest, interest for first month and interest for last month. Forth “hidden” number is reminder after dividing annual interest into monthly one. Let’s take an example scenario.

We want to save 10000 with the annual interest rate of 10% for 1 year. We are opening our savings account as I’m writing this post at 27th Oct 2015.

First things first – total amount of money we get – easy: 10000 * 10% = 1000.

Next we can calculate our average monthly interest: 1000 / 12 = 83.33. And here we can see our hidden fourth number because 83.33 * 12 = 999.96. As we talking about money (and as it’s the great explanation why you shouldn’t use floats for money calculations) we have missing 0.04. But as we are aware of this we can fix this on the first or last interest payment. I’ll add it for the last one.

But first let’s calculate the first interest payment. There are 4 days till end of the October so again easy calculation 4 / 31 * 83.33 = 10.75. Again. Money. I’m loosing some as the real result is 10.75225806451613. But that’s what the last interest payment is for :)

I know that last one could be calculated by checking date and proportion of days from the beginning of the month. Sometimes it’s needed but as we have annual plan all we need to do is to subtract first interest payment from average monthly one: 83.33 – 10.75 = 72.58. And we are nearly done. All we need to add here is the reminder we saved from division of annual interest by months: 72.58 + 0.04 = 72.62.

That’s all. Intentionally I’m not writing code to give you a try on that. It’s very interesting problem and great subject for short kata in the evening.

Let me know if you like this kind of articles without the code as I have an idea about focusing blog posts more on everyday problems than fancy code snippets for copy/paste ;)


After all I’ve created sample Scala Worksheet with the object solving problem I described. Moved the remainder to first payment to show more money on first month ;) Here’s the Gist.