Round Numbers to Decimal Places Safely
Round finite numbers to a bounded number of decimal places using exponent shifting, then format with fixed digits.
Code
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
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?
- 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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.