JavaScript Math.round() 方法



JavaScript 的 Math.round() 方法接受一個數值作為引數,將其四捨五入到最接近的整數並返回結果。

Math.round() 方法的工作原理如下:

  • 如果數字的小數部分小於 0.5,則 Math.round() 返回小於或等於 x 的最大整數。
  • 如果數字的小數部分等於或大於 0.5,則 Math.round() 返回大於或等於 x 的最小整數。

語法

以下是 JavaScript Math.round() 方法的語法:

Math.round(x);

引數

此方法僅接受一個引數。如下所述:

x: 要四捨五入的數字。

返回值

此方法返回給定數字最接近的整數。如果小數部分為 .5 或更大,則數字向上取整。否則,向下取整。

示例 1

在以下示例中,我們演示了 JavaScript Math.round() 方法的基本用法:

<html>
<body>
<script>
   let value1 = Math.round(5.49);
   document.write(value1, "<br>");

   let value2 = Math.round(5.50);
   document.write(value2, "<br>");

   let value3 = Math.round(5.99);
   document.write(value3);
</script>
</body>
</html>

輸出

如果我們執行上述程式,指定的正整數將被四捨五入到最接近的整數。

示例 2

在這裡,我們將負引數傳遞給 Math.round() 方法:

<html>
<body>
<script>
   let value1 = Math.round(-5.49);
   document.write(value1, "<br>");

   let value2 = Math.round(-5.50);
   document.write(value2, "<br>");

   let value3 = Math.round(-5.99);
   document.write(value3);
</script>
</body>
</html>

輸出

如果我們執行程式,它將返回“-5”,“-5”和“-6”作為結果。

示例 3

如果我們將“null”作為引數傳遞給此方法,則它將返回“0”作為結果:

<html>
<body>
<script>
   let value = Math.round(null);
   document.write(value);
</script>
</body>
</html>

輸出

如輸出所示,它返回了“null”。

示例 4

如果我們提供非數字或空數字作為此方法的引數,則它將返回“NaN”作為結果:

<html>
<body>
<script>
   let value1 = Math.round("Tutorialspoint");
   let value2 = Math.round();
   document.write(value1, "<br>", value2);
</script>
</body>
</html>

輸出

如輸出所示,它返回了“NaN”。

廣告