Percent Change and Signed Percentage Formatting

Calculate relative change between two numbers and format the result with fixed decimals, an explicit plus sign and locale-free output.

JavascriptData Integrity

Code

javascriptsnippet
17 lines
export function percentChange(previous, current) {
  if (!Number.isFinite(previous) || !Number.isFinite(current)) {
    throw new TypeError("previous and current must be finite numbers");
  }
  if (previous === 0) throw new RangeError("previous value must not be zero");
  return ((current - previous) / Math.abs(previous)) * 100;
}

export function formatPercentChange(value, digits = 1) {
  if (!Number.isFinite(value)) throw new TypeError("value must be a finite number");
  if (!Number.isInteger(digits) || digits < 0 || digits > 6) {
    throw new RangeError("digits must be an integer between 0 and 6");
  }
  const rounded = Number(value.toFixed(digits));
  const sign = rounded > 0 ? "+" : "";
  return sign + rounded.toFixed(digits) + "%";
}

How the snippet works

Percent Change and Signed Percentage Formatting keeps everything in the functions percentChange and formatPercentChange.

A guard precedes the TypeError and RangeError: bad state stops the flow there instead of continuing.

What to watch for

  • The guard previous === 0 short-circuits the flow with an early throw when its condition holds.

Applying it

The main signature reads export function percentChange(previous, current)

Import percentChange from the file and call it — the rest of the code is implementation detail.

Statements that matter

if (!Number.isFinite(value)) throw new TypeError("value must be a finite number");
if (previous === 0) throw new RangeError("previous value must not be zero");
throw new TypeError("previous and current must be finite numbers");

Interactive Tools for This Topic

FAQ

What does the snippet do with malformed data?
The code throws `TypeError` and `RangeError` — the guard `previous === 0` rejects bad states before the main logic runs. Handle it at the call site or let it propagate deliberately.
Is anything beyond the standard library required?
Nothing beyond the standard library — the snippet is dependency-free. The file defines `percentChange`, `formatPercentChange` at load time.