Round Numbers to Decimal Places Safely

Round finite numbers to a bounded number of decimal places using exponent shifting, then format with fixed digits.

TypescriptData Integrity

Code

typescriptsnippet
21 lines
function shiftDecimal(value: number, places: number): number {
  const [coefficient, exponent = "0"] = value.toString().split("e");
  return Number(coefficient + "e" + (Number(exponent) + places));
}

export function roundTo(value: number, decimals = 0): number {
  if (!Number.isFinite(value)) throw new TypeError("value must be a finite number");
  if (!Number.isInteger(decimals) || decimals < 0 || decimals > 15) {
    throw new RangeError("decimals must be an integer between 0 and 15");
  }
  const shifted = shiftDecimal(Math.abs(value), decimals);
  const rounded = Math.round(shifted);
  return Math.sign(value) * shiftDecimal(rounded, -decimals);
}

export function formatFixed(value: number, decimals = 2): string {
  if (!Number.isInteger(decimals) || decimals < 0 || decimals > 15) {
    throw new RangeError("decimals must be an integer between 0 and 15");
  }
  return roundTo(value, decimals).toFixed(decimals);
}

How the snippet works

Round Numbers to Decimal Places Safely keeps everything in the functions shiftDecimal, roundTo and formatFixed.

TypeError and RangeError is the guard’s signal — thrown at the branch, before any partial work happens.

Applying it

The main signature reads export function roundTo(value: number, decimals = 0)

The surface worth importing is roundTo; the helpers around it are private to the snippet.

Statements that matter

if (!Number.isFinite(value)) throw new TypeError("value must be a finite number");
throw new RangeError("decimals must be an integer between 0 and 15");
return Number(coefficient + "e" + (Number(exponent) + places));

Interactive Tools for This Topic

FAQ

What does the snippet do with malformed data?
Validation comes first — `TypeError` and `RangeError` marks the failure, before any partial work happens.
Does this require external packages?
No. It relies only on built-in language and platform APIs, so you can paste it into a project without installing anything. The file defines `shiftDecimal`, `roundTo`, `formatFixed` at load time.