Math.round()

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

Math.round() 静态方法返回一个数字四舍五入到最接近的整数后的值。

试一试

console.log(Math.round(0.9));
// Expected output: 1

console.log(Math.round(5.95), Math.round(5.5), Math.round(5.05));
// Expected output: 6 6 5

console.log(Math.round(-5.05), Math.round(-5.5), Math.round(-5.95));
// Expected output: -5 -5 -6

语法

js
Math.round(x)

参数

x

一个数字。

返回值

参数 x 四舍五入到最接近的整数后的值。

描述

如果参数的小数部分大于 0.5,则参数四舍五入到绝对值更大的下一个整数。如果小于 0.5,则参数四舍五入到绝对值更小的整数。如果小数部分恰好为 0.5,则参数将朝 +∞ 的方向四舍五入到下一个整数。

注意:这与许多语言中的 round() 函数不同,后者通常将半增量“远离零”四舍五入,对于小数部分恰好为 0.5 的负数会产生不同的结果。

Math.round(x)Math.floor(x + 0.5) 并不完全相同。当 x 为 -0 或 -0.5 ≤ x < 0 时,Math.round(x) 返回 -0,而 Math.floor(x + 0.5) 返回 0。但是,忽略这个差异和潜在的精度误差,Math.round(x)Math.floor(x + 0.5) 通常是等效的。

由于 round()Math 的静态方法,因此您始终使用 Math.round() 来调用它,而不是使用您创建的 Math 对象的某个方法(Math 没有构造函数)。

示例

使用 round

js
Math.round(-Infinity); // -Infinity
Math.round(-20.51); // -21
Math.round(-20.5); // -20
Math.round(-0.1); // -0
Math.round(0); // 0
Math.round(20.49); // 20
Math.round(20.5); // 21
Math.round(42); // 42
Math.round(Infinity); // Infinity

规范

规范
ECMAScript® 2026 语言规范
# sec-math.round

浏览器兼容性

另见