How to calculate compound interest in Node.js

1 Answer

0 votes
function calculateCompoundInterest(principal, rate, years) {
  // Validate input: all values must be non-negative
  if (principal < 0 || rate < 0 || years < 0) {
    console.error("Error: Principal, rate, and years must be non-negative values.");
    return -1;
  }

  // Calculate total amount using the compound interest formula
  const amount = principal * Math.pow(1 + rate / 100, years);

  // Return compound interest (total amount - principal)
  return amount - principal;
}

const principal = 120000; // Initial investment
const rate = 3.7;         // Annual interest rate in percent
const years = 5;          // Investment duration in years

const compoundInterest = calculateCompoundInterest(principal, rate, years);

if (compoundInterest >= 0) {
  console.log(`Principal Amount: ${principal.toFixed(2)}`);
  console.log(`Annual Interest Rate: ${rate.toFixed(2)}%`);
  console.log(`Years: ${years.toFixed(2)}`);
  console.log(`Compound Interest: ${compoundInterest.toFixed(2)}`);
  console.log(`Total Amount: ${(principal + compoundInterest).toFixed(2)}`);
}




/*
run:

Principal Amount: 120000.00
Annual Interest Rate: 3.70%
Years: 5.00
Compound Interest: 23904.72
Total Amount: 143904.72

*/

 



answered Aug 30, 2025 by avibootz

Related questions

...