I’m trying to make a simple credit card repayment calculator script but seem to be having a problem with a “while” loop. It works for low numbers, but when you start putting in higher numbers it freezes the browser, then you have to quit and reopen.
Here is the JavaScript (jQuery) I have:
$('#calculate').click(function()
{
var currentBalance = parseFloat($('#current_balance').val().substring(1)); // substring so it doesnt grab the £ sign
var interestRate = parseFloat($('#interest_rate').val());
var interestType = $('#interest_type').val();
var monthlyPayment = parseFloat($('#monthly_payment').val().substring(1));
var totalInterest = 0;
var interest = 0;
var months = 0;
while(currentBalance > 0) // while there is still a balance on the card run the following
{
interest = (currentBalance/100)*interestRate; // find interest amount for this month
currentBalance = currentBalance+interest; // add the interest to the balance
currentBalance = currentBalance-monthlyPayment; // subtract monthly payment from balance
totalInterest = totalInterest+interest; // total amount of interest paid
months++;
}
var years = parseInt(months / 12);
var remainingMonths = months % 12;
totalInterest = Math.round(totalInterest);
$('#clear_balance').val(years+' years and '+remainingMonths+' months');
$('#interest_paid').val('£'+totalInterest);
});
and here is my HTML:
<table id="card-info">
<tbody>
<tr>
<td><label for="current_balance">Current balance</label></td>
<td><input type="text" id="current_balance" /></td>
</tr>
<tr>
<td><label for="interest_rate">Interest rate</label></td>
<td>
<input type="text" id="interest_rate" />
<select id="interest_type">
<option value="monthly">Monthly</option>
<option value="yearly">Yearly</option>
</select>
</td>
</tr>
<tr>
<td><label for="monthly_payment">Monthly payment</label></td>
<td><input type="text" id="monthly_payment" /></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td colspan="2"><button id="calculate">Calculate</button></td>
</tr>
</tbody>
</table>
</div>
<div id="results">
<table id="results-info">
<tbody>
<tr>
<td>
<label for="clear_balance">Time to clear balance</label><br />
<input type="text" id="clear_balance" />
</td>
<td>
<label for="interest_paid">Total interest paid</label><br />
<input type="text" id="interest_paid" />
</td>
</tr>
</tbody>
</table>
Is there anything I am doing wrong?
Your code doesn’t account for the case where the montly payment is insufficient to cover the interest charged each month.
In those circumstances it’ll go into an infinite loop, because the loan never gets paid off!