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

瀏覽器相容性

另見