roundToDecimal
Rounds a number to a specified number of decimal places.
1/**
2 * Rounds a number to a specified number of decimal places.
3 *
4 * @param num - The number to round.
5 * @param decimals - The number of decimal places.
6 * @returns The rounded number.
7 */
8export function roundToDecimal(num: number, decimals: number): number {
9 const factor = 10 ** decimals;
10 return Math.round(num * factor) / factor;
11}
Precision Control
Allows precise rounding to any number of decimal places, which is essential in domains like finance or measurement.
Avoids Floating-Point Drift
Reduces common floating-point inaccuracies by scaling before rounding.
Lightweight and Fast
Performs rounding with minimal overhead using native arithmetic operations.
Decoupled from String Conversion
Returns a true number, unlike some approaches that rely on
.toFixed()
which returns a string.
Tests | Examples
1test('roundToDecimal - basic rounding', () => {
2 expect(roundToDecimal(3.14159, 2)).toBe(3.14);
3});
4
5test('roundToDecimal - rounds up', () => {
6 expect(roundToDecimal(1.005, 2)).toBe(1.01);
7});
8
9test('roundToDecimal - rounds down', () => {
10 expect(roundToDecimal(1.004, 2)).toBe(1.0);
11});
12
13test('roundToDecimal - zero decimals', () => {
14 expect(roundToDecimal(7.89, 0)).toBe(8);
15});
16
17test('roundToDecimal - negative number', () => {
18 expect(roundToDecimal(-3.456, 1)).toBe(-3.5);
19});
20
21test('roundToDecimal - no rounding needed', () => {
22 expect(roundToDecimal(2.5, 1)).toBe(2.5);
23});
24
25test('roundToDecimal - high precision', () => {
26 expect(roundToDecimal(Math.PI, 10)).toBeCloseTo(3.1415926536, 10);
27});
Common Use Cases
Financial Calculations
Round currency values to two decimal places for accurate billing or display.
UI Display Formatting
Present numbers in tooltips, labels, or charts with consistent precision.
Scientific or Statistical Results
Round results to a required level of precision for analysis or reporting.
User Input Normalization
Clean up user-entered numeric values (e.g., weights, lengths) to avoid excessive decimal precision.
Export or API Response Formatting
Ensure returned data values conform to expected decimal formats before serialization or export.