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 已作为结果返回。