當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


JavaScript Math round()用法及代碼示例

在本教程中,我們將借助示例了解 JavaScript Math.round() 函數。

Math.round()函數返回四舍五入到最接近整數的數字。那是,3.87四舍五入為43.45四舍五入為3.

示例

let number = 3.87;

// round the number to nearest integer
let roundedNumber = Math.round(number);
console.log(roundedNumber);

// Output: 4

數學.round() 語法

用法:

Math.round(x)

round() 是一個靜態方法,使用 Math 類名調用。

Math.round() 參數

Math.round() 函數接受:

  • x - 一個數字

從數學返回值。round()

Math.round() 返回四舍五入到最接近整數的數值,如下所示:

  • 如果小數部分 > 0.5,x四舍五入為絕對值較高的整數。
  • 如果小數部分 < 0.5,x被四舍五入為具有較低絕對值的整數。
  • 如果小數部分 = 0.5,x在 方向上四舍五入到下一個整數+∞.

示例:使用數學。round()

// using Math.round()
var num = Math.round(1.8645);
console.log(num); // 2

var num = Math.round(10.49);
console.log(num); // 10

var num = Math.round(4.5);
console.log(num); // 5

var num = Math.round(-4.5);
console.log(num); // -4

// Returns 0 for null
var num = Math.round(null);
console.log(num); // 0

// Returns NaN for non-numeric types
var num = Math.round("JavaScript");
console.log(num); // NaN

輸出

2
10
5
-4
0
NaN

注意: Math.round()返回0為了null而不是NaN.

相關用法


注:本文由純淨天空篩選整理自 JavaScript Math round()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。