MORTGAGE PAYMENT CALCULATOR
// Function to calculate monthly payment
function calculateMonthlyPayment(principal, annualInterestRate, years) {
/**
* Calculate the monthly mortgage payment using the formula:
* M = P[r(1+r)^n]/[(1+r)^n - 1]
*
* Args:
* principal (number): Loan amount.
* annualInterestRate (number): Annual interest rate in percent.
* years (number): Loan term in years.
*
* Returns:
* number: Monthly payment.
*/
const monthlyInterestRate = (annualInterestRate / 100) / 12;
const totalPayments = years * 12;
if (monthlyInterestRate === 0) {
// Handle case for 0% interest
return principal / totalPayments;
} else {
return principal * (
monthlyInterestRate * Math.pow(1 + monthlyInterestRate, totalPayments)
) / (Math.pow(1 + monthlyInterestRate, totalPayments) - 1);
}
}
// Function to display amortization schedule
function displayAmortizationSchedule(principal, annualInterestRate, years) {
/**
* Display the amortization schedule of the mortgage.
*
* Args:
* principal (number): Loan amount.
* annualInterestRate (number): Annual interest rate in percent.
* years (number): Loan term in years.
*/
const monthlyPayment = calculateMonthlyPayment(principal, annualInterestRate, years);
const monthlyInterestRate = (annualInterestRate / 100) / 12;
let remainingBalance = principal;
console.log("Payment #\tInterest\tPrincipal\tRemaining Balance");
for (let paymentNumber = 1; paymentNumber <= years * 12; paymentNumber++) {
const interestPayment = remainingBalance * monthlyInterestRate;
const principalPayment = monthlyPayment - interestPayment;
remainingBalance -= principalPayment;
console.log(`${paymentNumber}\t${interestPayment.toFixed(2)}\t${principalPayment.toFixed(2)}\t${remainingBalance > 0 ? remainingBalance.toFixed(2) : 0}`);
}
}
// Input and user interaction
const principal = parseFloat(prompt("Enter the loan amount (principal): "));
const annualInterestRate = parseFloat(prompt("Enter the annual interest rate (in %): "));
const years = parseInt(prompt("Enter the term length (in years): "), 10);
if (!isNaN(principal) && !isNaN(annualInterestRate) && !isNaN(years)) {
const monthlyPayment = calculateMonthlyPayment(principal, annualInterestRate, years);
console.log(`\nYour monthly payment will be: $${monthlyPayment.toFixed(2)}\n`);
const showSchedule = prompt("Do you want to see the amortization schedule? (yes/no): ").toLowerCase();
if (showSchedule === "yes" || showSchedule === "y") {
displayAmortizationSchedule(principal, annualInterestRate, years);
}
} else {
console.log("Invalid input. Please enter valid numeric values.");
}