I am working on a project that will determine the time to pay off a credit card and the interest paid based on the current balance, the interest rate, and the monthly payments m
The problem is operator precedence. The ?:
conditional operator has lower precedence than +
, so the :
part contains all the concatenated strings, not just the ""
string that should replace the year. So you display the year when yearChange
is true, you display everything else only when yearChange
is false.
The solution is to wrap the conditional expression in parentheses.
function displayWelcome() {
console.log("Welcome! \nThis program will determine the time to pay off a credit card and the interest paid based on the current balance, the interest rate, and the monthly payments made.")
}
function calculateminimumPaymentment(balance, minimumPaymentRate) {
return Math.max(20, balance * minimumPaymentRate);
}
function displayPayments(balance, interest, minimumPayment) {
console.log("Balance on your credit card: $" + balance.toFixed(2))
console.log("Interest Rate: " + (interest * 100) + "%")
console.log("Assuming a minimum payment of 2% of the balance ($20 min)")
console.log("Your minimum payment would be: $" + minimumPayment)
console.log("\nYear Balance Payment # Interest Paid Minimum Payment")
var year = 1;
var payments = 1;
var interestPaid = 0;
var yearChange;
while (balance > 0) {
yearChange = false;
if (payments % 12 == 0) {
year++
yearChange = true;
}
interestPaid += balance * interest / 12;
balance = Math.max(0, balance - (minimumPayment - balance * interest / 12));
minimumPayment = Math.max(20, balance * minimumPaymentRate);
console.log((yearChange ? year : "") + " " + balance.toFixed(2) + " " + payments + " " + interestPaid.toFixed(2) + " " + minimumPayment.toFixed(2));
payments++;
}
}
var balance = 1500;
var minimumPaymentRate = 0.02;
var interest = 0.18;
displayWelcome()
var minimumPayment = calculateminimumPaymentment(balance, minimumPaymentRate);
displayPayments(balance, interest, minimumPayment);