JavaScript Math.fround() 方法



JavaScript 的 Math.fround() 方法用於返回給定數字最接近的 32 位單精度浮點數表示。它接受一個引數 "x",即我們要轉換為其最接近的單精度浮點數表示的數字。如果提供的引數是 NaN,則此方法返回 NaN。如果提供 (+) Infinity 或 (-) Infinity 作為引數,則分別返回 (+) Infinity 和 (-) Infinity。

語法

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

Math.fround(doubleFloat)

引數

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

  • doubleFloat: 我們要查詢其最接近的單精度浮點數表示的數字。

返回值

此方法返回給定數字最接近的 32 位單精度浮點數表示。

示例 1

在下面的示例中,我們演示了 JavaScript Math.fround() 方法的使用:

<html>
<body>
<script>
   const num1 = Math.fround(5.80);
   const num2 = Math.fround(5.50);
   const num3 = Math.fround(5.49);

   const num4 = Math.fround(-5.80);
   const num5 = Math.fround(-5.50);
   const num6 = Math.fround(-5.49);
   document.write(num1, "<br>",num2 , "<br>", num3, "<br>", num4, "<br>", num5, "<br>", num6, "<br>");
</script>
</body>
</html>

輸出

執行上述程式後,此方法將返回給定數字最接近的單精度浮點數表示。

示例 2

如果我們將 "0" 作為引數提供給此方法,它將返回 0 作為結果:

<html>
<body>
<script>
   const num = Math.fround(0);
   document.write(num);
</script>
</body>
</html>

輸出

正如我們在輸出中看到的,返回的結果是 0。

示例 3

如果提供 NaN 作為引數,結果也將是 NaN:

<html>
<body>
<script>
   const num = Math.fround(NaN);
   document.write(num);
</script>
</body>
</html>

輸出

正如我們在輸出中看到的,返回的結果是 NaN。

示例 4

如果提供 "Infinity" 作為引數,結果將是 Infinity:

<html>
<body>
<script>
   const num = Math.fround(Infinity);
   document.write(num);
</script>
</body>
</html>

輸出

正如我們在輸出中看到的,返回的結果是 Infinity。

廣告