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.
Code
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 === 0short-circuits the flow with an earlythrowwhen 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
Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.GCD & LCM CalculatorFind the greatest common divisor and least common multiple of two or more integers, computed exactly with BigInt.Indentation ConverterConvert leading indentation between tabs and spaces at a chosen width, leaving inner content untouched.JSON Formatter & ValidatorFormat, beautify, and validate JSON data with configurable indentation. Instantly catches syntax errors and displays a pretty-printed tree structure.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.