Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

percentChange

Calculates the percentage change from an old value to a new value.

TypeScript
Copied!
1/**
2 * Calculates the percentage change from an old value to a new value.
3 *
4 * @param oldValue - The original value.
5 * @param newValue - The new value.
6 * @returns Percentage change, positive or negative.
7 */
8export function percentChange(oldValue: number, newValue: number): number {
9  if (oldValue === 0) {
10    return newValue === 0 ? 0 : Infinity * Math.sign(newValue);
11  }
12  return ((newValue - oldValue) / Math.abs(oldValue)) * 100;
13}
  • Directional Awareness

    Preserves the sign of the change, clearly indicating increases (positive) or decreases (negative).

  • Zero Handling Logic

    Gracefully handles cases where the original value is zero, avoiding division-by-zero errors while conveying meaningful outcomes.

  • Mathematically Sound

    Uses the absolute value of the original value to ensure consistency in percentage calculations.

  • Compact and Clear

    Cleanly expresses a common mathematical operation with minimal and readable code.

Tests | Examples

TypeScript
Copied!
1test('percentChange - increase', () => {
2  expect(percentChange(100, 150)).toBe(50);
3});
4
5test('percentChange - decrease', () => {
6  expect(percentChange(200, 150)).toBe(-25);
7});
8
9test('percentChange - no change', () => {
10  expect(percentChange(42, 42)).toBe(0);
11});
12
13test('percentChange - from zero to positive', () => {
14  expect(percentChange(0, 10)).toBe(Infinity);
15});
16
17test('percentChange - from zero to negative', () => {
18  expect(percentChange(0, -10)).toBe(-Infinity);
19});
20
21test('percentChange - both zero', () => {
22  expect(percentChange(0, 0)).toBe(0);
23});

Common Use Cases

  • KPI Tracking and Reporting

    Calculate percentage growth or decline in metrics like revenue, user count, or engagement.

  • Financial Analysis

    Show price changes, profit margins, or cost variations over time.

  • Monitoring and Alerts

    Trigger warnings or UI indicators when a value increases or drops significantly.

  • Performance Comparison

    Evaluate percent improvement or regression between code versions, experiments, or A/B tests.

  • Visualization Labels

    Annotate charts and graphs with change indicators to give users quick insights.

Codebase: Utilities -> Numbers -> percentChange | Yevhen Klymentiev