How to calculate % change from X to Y in TypeScript

1 Answer

0 votes
function percentChange(x: number, y: number): number {
    return ((y - x) / Math.abs(x)) * 100.0;
}

function describeChange(x: number, y: number): string {
    const pct: number = percentChange(x, y);

    if (pct > 0) {
        return `From ${x.toFixed(1)} to ${y.toFixed(1)} is a ${pct.toFixed(2)}% increase (+${pct.toFixed(2)}%)`;
    } else if (pct < 0) {
        return `From ${x.toFixed(1)} to ${y.toFixed(1)} is a ${Math.abs(pct).toFixed(2)}% decrease (${pct.toFixed(2)}%)`;
    } else {
        return `From ${x.toFixed(1)} to ${y.toFixed(1)} is no change`;
    }
}

console.log(describeChange(-80.0, 120.0));
console.log(describeChange(120.0, 30.0));



/*
run:

From -80.0 to 120.0 is a 250.00% increase (+250.00%)
From 120.0 to 30.0 is a 75.00% decrease (-75.00%)

*/

 



answered May 29 by avibootz
...