Skip to content

roundTo

Edit

Rounds finite numbers safely across decimal positions and extreme magnitudes.

roundTo.ts
const shiftExponent = (value: number, exponent: number): number => {
if (value === 0) return value;
const [coefficient, current = "0"] = String(value).split("e");
return Number(`${coefficient}e${Number(current) + exponent}`);
};
/** Rounds a finite number with Math.round tie semantics and guarded exponent shifts. */
export const roundTo = (value: number, precision: number = 0): number => {
if (!Number.isFinite(value)) throw new RangeError("value must be finite");
if (!Number.isSafeInteger(precision) || Math.abs(precision) > 100) {
throw new RangeError("precision must be a safe integer between -100 and 100");
}
if (precision === 0) return Math.round(value);
const shifted = shiftExponent(value, precision);
if (!Number.isFinite(shifted)) {
// A positive shift can overflow only when the requested decimal place is far
// below the number's representable precision, so rounding cannot change it.
if (precision > 0) return value;
throw new RangeError("rounded value is outside the finite number range");
}
const result = shiftExponent(Math.round(shifted), -precision);
if (!Number.isFinite(result)) {
throw new RangeError("rounded value is outside the finite number range");
}
return result;
};
Terminal
wget -O src/lib/roundTo.ts https://raw.githubusercontent.com/jrTilak/lazykit/HEAD/registry/functions/roundTo.ts
roundTo.example.ts
import { roundTo } from "./roundTo";
const price = roundTo(1.005, 2);
// 1.01
const nearestHundred = roundTo(1_250, -2);
// 1300
  • value (number) — Finite number to round.
  • precision (number) — Integer from -100 to 100; defaults to 0.
  • Negative precision rounds positions left of the decimal point.
  • Halfway values follow Math.round, toward positive infinity, including negative ties.
  • Negative results rounded to zero preserve -0.
  • Extreme positive precision returns the original finite value when the requested decimal place is finer than the number can represent; no finite input silently produces NaN or infinity.