generate an amortized loan calculator in javascript

index.tsx
// Define inputs
const principal = 100000;
const interestRate = 5;
const years = 15;

// Calculate monthly interest rate and number of payments
const monthlyInterestRate = (interestRate / 100) / 12;
const numberOfPayments = years * 12;

// Calculate monthly payment
const x = Math.pow(1 + monthlyInterestRate, numberOfPayments);
const monthlyPayment = (principal * x * monthlyInterestRate) / (x - 1);

// Calculate amortization schedule
let balance = principal;
let amortizationSchedule = [];
for (let i = 1; i <= numberOfPayments; i++) {
  const interest = balance * monthlyInterestRate;
  const principalPayment = monthlyPayment - interest;
  balance = balance - principalPayment;
  amortizationSchedule.push({ 
    month: i, 
    balance: balance, 
    principal: principalPayment, 
    interest: interest, 
    totalInterest: totalInterest + interest 
  })
}

// Display results
console.log(`Loan: $${principal.toFixed(2)} at ${interestRate}% interest for ${years} years`);
console.log(`Monthly Payment: $${monthlyPayment.toFixed(2)}`);
console.log(`Total Interest Paid: $${totalInterest.toFixed(2)}`);

// Display amortization schedule
amortizationSchedule.forEach(month => {
  console.log(`Month ${month.month}: $${month.principal.toFixed(2)} principal, $${month.interest.toFixed(2)} interest, $${month.balance.toFixed(2)} balance`);
});
1344 chars
39 lines

This code defines the inputs (principal, interest rate, and number of years), calculates the monthly payment, and generates an amortization schedule. The results are displayed in the console, including the total interest paid and the details for each month's payment.

gistlibby LogSnag