CyrefJS
CCyrefJS
فا
Back to documentation
Number/Since 1.38.0

roundTo

Rounds a number to the specified number of decimal places.

roundTo(value, decimals):number

Parameters

valuenumberrequired

The number to round.

decimalsnumberrequired

The number of decimal places to preserve. Must be an integer.

Returns

number

Returns 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

01

Basic usage

Rounds the value to two decimal places.

TypeScript
const result = roundTo(4.126, 2);

console.log(result);
// 4.13
02

Value already at the precision

A value that already has the requested precision remains unchanged.

TypeScript
console.log(roundTo(4.12, 2));
// 4.12
03

Zero decimals

When decimals is 0, the value is rounded to the nearest integer using Math.round.

TypeScript
console.log(roundTo(4.4, 0));
// 4

console.log(roundTo(4.6, 0));
// 5
04

Negative values

Negative values are rounded using the same calculation.

TypeScript
console.log(roundTo(-4.126, 2));
// -4.13

console.log(roundTo(-4.124, 2));
// -4.12
05

More decimal places

A larger decimals value preserves more decimal places.

TypeScript
console.log(roundTo(3.14159, 3));
// 3.142

console.log(roundTo(3.14159, 4));
// 3.1416
06

Negative decimals

Negative decimal places round the value at positions to the left of the decimal point.

TypeScript
console.log(roundTo(1234, -2));
// 1200

console.log(roundTo(1250, -2));
// 1300
07

Infinity

Positive and negative Infinity are returned unchanged.

TypeScript
console.log(roundTo(Infinity, 2));
// Infinity

console.log(roundTo(-Infinity, 2));
// -Infinity
08

NaN

NaN is rejected and causes a RangeError.

TypeScript
roundTo(NaN, 2);
// RangeError: roundTo: value must not be NaN
09

Non-integer decimals

The decimals argument must be an integer.

TypeScript
roundTo(4.126, 2.5);
// RangeError: roundTo: decimals must be an integer
Built with@cyref/js·Official documentation