1.38.0roundTo
Rounds a number to the specified number of decimal places.
roundTo(value, decimals):numberParameters
valuenumberrequiredThe number to round.
decimalsnumberrequiredThe number of decimal places to preserve. Must be an integer.
Returns
numberReturns the value rounded to the specified decimal precision.
Errors
Throws a RangeError if value is NaN.
Throws a RangeError if decimals is not an integer.
Examples
Basic usage
Rounds the value to two decimal places.
const result = roundTo(4.126, 2);
console.log(result);
// 4.13Value already at the precision
A value that already has the requested precision remains unchanged.
console.log(roundTo(4.12, 2));
// 4.12Zero decimals
When decimals is 0, the value is rounded to the nearest integer using Math.round.
console.log(roundTo(4.4, 0));
// 4
console.log(roundTo(4.6, 0));
// 5Negative values
Negative values are rounded using the same calculation.
console.log(roundTo(-4.126, 2));
// -4.13
console.log(roundTo(-4.124, 2));
// -4.12More decimal places
A larger decimals value preserves more decimal places.
console.log(roundTo(3.14159, 3));
// 3.142
console.log(roundTo(3.14159, 4));
// 3.1416Negative decimals
Negative decimal places round the value at positions to the left of the decimal point.
console.log(roundTo(1234, -2));
// 1200
console.log(roundTo(1250, -2));
// 1300Infinity
Positive and negative Infinity are returned unchanged.
console.log(roundTo(Infinity, 2));
// Infinity
console.log(roundTo(-Infinity, 2));
// -InfinityNaN
NaN is rejected and causes a RangeError.
roundTo(NaN, 2);
// RangeError: roundTo: value must not be NaNNon-integer decimals
The decimals argument must be an integer.
roundTo(4.126, 2.5);
// RangeError: roundTo: decimals must be an integer