How to calculate the percentage change between two values in TypeScript

1 Answer

0 votes
function percentageChange(oldValue: number, newValue: number): number {
  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: number = percentageChange(oldValue, newValue);
  console.log(`Percentage change: ${change.toFixed(2)}%`);
} catch (err) {
  console.error("Error:", (err as Error).message);
}




/*
run:

"Percentage change: 26.67%" 

*/

 



answered Mar 16 by avibootz
...