Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Math.round: nearest integer

Math.round converts its argument to Number and returns the nearest integral Number, breaking ties toward +Infinity.

Version: ECMAScript 1 onward; example target: Node.js 24.22.2

Syntax

Math.round(x)

Math.round(x) applies ToNumber. If two integral Numbers are equally close, it chooses the one closer to +Infinity: 2.5 becomes 3, but -2.5 becomes -2. An already integral argument, NaN, +Infinity, -Infinity, +0, or -0 is returned with that special value preserved.

For values from -0.5 inclusive to 0 exclusive, the result is -0; detect it with Object.is or a reciprocal. Therefore Math.round(x) is not always equivalent to Math.floor(x + 0.5), which can lose the zero sign, while the addition can also round a very large x.

A numeric string is converted, a missing argument produces NaN, and a Symbol or BigInt throws TypeError. The function has existed since ECMAScript 1 and is not a constructor. It rounds numeric values rather than formatting text; handle decimal-place presentation separately and account for binary64 rounding.

Examples

console.log([2.3, 2.5, -2.5, -2.6].map(Math.round).join(","));
console.log(Object.is(Math.round(-0.5), -0), Object.is(Math.round(-0.1), -0));
console.log(Math.round("4.6"), Math.round(Infinity));
console.log(Number.isNaN(Math.round()), Object.is(Math.round(-0), -0));
try { Math.round(3n); } catch (error) { console.log(error instanceof TypeError); }

Result

2,3,-2,-3
true true
5 Infinity
true true
true

Math.round → ties toward +Infinity and preserved -0

Sources