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。

广告
© . All rights reserved.