Math.fround()

Math.fround() 静态方法返回数字最接近的 32 位单精度 浮点表示形式。

¥The Math.fround() static method returns the nearest 32-bit single precision float representation of a number.

Try it

语法

¥Syntax

js
Math.fround(doubleFloat)

参数

¥Parameters

doubleFloat

一个号码。

返回值

¥Return value

x 最接近的 32 位单精度 浮点表示。

¥The nearest 32-bit single precision float representation of x.

描述

¥Description

JavaScript 内部使用 64 位双浮点数,提供非常高的精度。但是,有时你可能会使用 32 位浮点数,例如,如果你正在从 Float32Array 读取值。这可能会造成混乱:即使数字看起来相同,检查 64 位浮点数和 32 位浮点数是否相等也可能会失败。

¥JavaScript uses 64-bit double floating-point numbers internally, which offer a very high precision. However, sometimes you may be working with 32-bit floating-point numbers, for example if you are reading values from a Float32Array. This can create confusion: checking a 64-bit float and a 32-bit float for equality may fail even though the numbers are seemingly identical.

为了解决这个问题,可以使用 Math.fround() 将 64 位浮点数转换为 32 位浮点数。在内部,JavaScript 继续将数字视为 64 位浮点数,它只是对尾数的第 23 位执行 "四舍五入到偶数",并将所有后续尾数位设置为 0。如果数字超出 32 位浮点数的范围,则返回 Infinity-Infinity

¥To solve this, Math.fround() can be used to cast the 64-bit float to a 32-bit float. Internally, JavaScript continues to treat the number as a 64-bit float, it just performs a "round to even" on the 23rd bit of the mantissa, and sets all following mantissa bits to 0. If the number is outside the range of a 32-bit float, Infinity or -Infinity is returned.

因为 fround()Math 的静态方法,所以你始终将其用作 Math.fround(),而不是用作你创建的 Math 对象的方法(Math 不是构造函数)。

¥Because fround() is a static method of Math, you always use it as Math.fround(), rather than as a method of a Math object you created (Math is not a constructor).

示例

¥Examples

使用 Math.fround()

¥Using Math.fround()

数字 1.5 可以在二进制数字系统中精确表示,并且在 32 位和 64 位中是相同的:

¥The number 1.5 can be precisely represented in the binary numeral system, and is identical in 32-bit and 64-bit:

js
Math.fround(1.5); // 1.5
Math.fround(1.5) === 1.5; // true

然而,数字 1.337 无法在二进制数字系统中精确表示,因此它在 32 位和 64 位中有所不同:

¥However, the number 1.337 cannot be precisely represented in the binary numeral system, so it differs in 32-bit and 64-bit:

js
Math.fround(1.337); // 1.3370000123977661
Math.fround(1.337) === 1.337; // false

2 150 2^150

对于 32 位浮点数来说太大,因此返回 Infinity

¥is too big for a 32-bit float, so Infinity is returned:

js
2 ** 150; // 1.42724769270596e+45
Math.fround(2 ** 150); // Infinity

规范

Specification
ECMAScript Language Specification
# sec-math.fround

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看