How to calculate the percentage change between two values in JavaScript

1 Answer

0 votes
function percentageChange(oldValue, newValue) {
  if (oldValue === 0) {
    throw new Error("oldValue cannot be zero");
  }
  return ((newValue - oldValue) / oldValue) * 100;
}

const oldValue = 45.0;
const newValue = 57.0;

try {
  const change = percentageChange(oldValue, newValue);
  console.log(`Percentage change: ${change.toFixed(2)}%`);
} catch (err) {
  console.error("Error:", err.message);
}



/*
run:

Percentage change: 26.67%

*/

 



answered Mar 16 by avibootz
...