Math.fround()
方法返回一个数字的 nearest 32 位单精度浮点表示。
示例
// calculate the nearest 32-bit single
// precision float representation of 5.05
var num = Math.fround(5.05);
console.log(num);
// Output: 5.050000190734863
fround() 语法
fround()
方法的语法是
Math.fround(doubleFloat)
在此,fround()
是一个静态方法。因此,我们需要使用类名 Math
来访问该方法。
fround() 参数
fround()
方法接受
- doubleFloat - 一个数字。
fround() 返回值
fround()
方法返回
- 给定数字的 nearest 32 位单精度浮点表示。
- 对于非数字参数,返回
NaN
。
示例 1:JavaScript Math.fround()
// find the nearest 32-bit single precision float representation of 1.5
var num1 = Math.fround(1.5);
console.log(num1);
// find the nearest 32-bit single precision float representation of 1.337
var num2 = Math.fround(1.337);
console.log(num2);
输出
1.5 1.3370000123977661
在上面的例子中:
Math.fround(1.5)
计算 1.5 的 nearest 32 位单精度浮点表示。Math.fround(1.337)
计算 1.337 的 nearest 32 位单精度浮点表示。
注意: JavaScript 在内部使用 64 位双精度浮点数。
在上面的示例中,我们可以看到可以完美表示为二进制数系的数字(如 1.5)具有相同的 32 位单精度浮点表示。
然而,一些不能完美表示的数字(如 1.337 或 5.05)在 32 位和 64 位之间存在差异。
示例 2:fround() 与大数
// find the nearest 32-bit single precision float representation of 2 ** 130
var num = Math.fround(2 ** 130);
console.log(num);
// Output: Infinity
在上面的示例中,我们使用 Math.fround()
来计算一个非常大的数字的 nearest 32 位单精度浮点表示:2 ** 130
,即 1.361129467683754e+39。
输出表明,对于非常大的数字,结果是 Infinity
。
另请阅读