percentDiff
Calculates the percentage difference between two numbers.
1/**
2 * Calculates the percentage difference between two numbers.
3 *
4 * @param a - The original number.
5 * @param b - The new number.
6 * @returns The percent difference from 'a' to 'b'.
7 */
8export function percentDiff(a: number, b: number): number {
9 if (a === 0) {
10 return b === 0 ? 0 : Infinity;
11 }
12 return ((b - a) / Math.abs(a)) * 100;
13}
Handles Zero Safely
Includes logic to avoid division-by-zero errors and distinguish between zero-to-zero and zero-to-nonzero cases.
Directional Insight
Preserves the sign of the difference, indicating whether the value increased or decreased.
Mathematically Accurate
Uses absolute value of the base (
a
) to correctly calculate percentage change relative to magnitude.Concise and Readable
Simple logic with clear structure, making it easy to understand and maintain.
Tests | Examples
1test('percentDiff - positive increase', () => {
2 expect(percentDiff(100, 150)).toBe(50);
3});
4
5test('percentDiff - positive decrease', () => {
6 expect(percentDiff(200, 150)).toBeCloseTo(-25);
7});
8
9test('percentDiff - no change', () => {
10 expect(percentDiff(42, 42)).toBe(0);
11});
12
13test('percentDiff - zero to non-zero (infinity)', () => {
14 expect(percentDiff(0, 100)).toBe(Infinity);
15});
16
17test('percentDiff - zero to zero', () => {
18 expect(percentDiff(0, 0)).toBe(0);
19});
20
21test('percentDiff - handles negative base', () => {
22 expect(percentDiff(-100, -50)).toBe(50);
23 expect(percentDiff(-100, -200)).toBe(-100);
24});
Common Use Cases
Analytics and Dashboards
Show percentage change in metrics like revenue, traffic, or conversion rate over time.
Finance and Investment
Calculate percent gain or loss in stock prices, portfolio value, or earnings reports.
Reporting and Comparison
Highlight performance changes between current and previous periods in reports.
User Feedback or Notifications
Notify users when a tracked value changes significantly in either direction.
Testing and Benchmarking
Evaluate percent improvement or regression in performance metrics between versions or builds.