roundTo
EditRounds finite numbers safely across decimal positions and extreme magnitudes.
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;};Download
Section titled “Download”wget -O src/lib/roundTo.ts https://raw.githubusercontent.com/jrTilak/lazykit/HEAD/registry/functions/roundTo.tstemp_dir="$(mktemp -d)" && bunx degit jrTilak/lazykit/registry/functions "$temp_dir" && mv "$temp_dir/roundTo.ts" src/lib/roundTo.ts && rm -r "$temp_dir"Examples
Section titled “Examples”import { roundTo } from "./roundTo";
const price = roundTo(1.005, 2);// 1.01
const nearestHundred = roundTo(1_250, -2);// 1300value(number) — Finite number to round.precision(number) — Integer from-100to100; defaults to0.- 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
NaNor infinity.