← 中文资源

简体中文版本

fround 把双精度舍入到 float32

Math.fround 把双精度数舍入到最近的 float32 值再以双精度存回:1.1 产生漂移、1.5 完整保留,尾数只有 24 位所以 2^24+1 舍回 2^24,超范围溢出为 Infinity。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

1.1 -> 1.100000023841858
exact round trip: false
1.5 -> 1.5 true
16777217 -> 16777216
16777216 -> 16777216
huge -> Infinity

使用要点

  • 直接运行文件,输出会带上标签,比如 1.1 ->、exact round trip:、1.5 ->——输出的每一行都能指回产生它的那次调用。

常见问题

这段代码会引入外部包吗?

不涉及外部包,每个调用都落在内建 API 上。

代码示例

// Math.fround rounds a double to the nearest float32 value, kept as a double
console.log('1.1 ->', Math.fround(1.1));
console.log('exact round trip:', Math.fround(1.1) === 1.1);

// Values representable in float32 survive unchanged
console.log('1.5 ->', Math.fround(1.5), Math.fround(1.5) === 1.5);

// float32 has a 24-bit mantissa, so integers past 2^24 round down
console.log('16777217 ->', Math.fround(16777217)); // 2^24 + 1
console.log('16777216 ->', Math.fround(16777216)); // 2^24 itself is exact

// Doubles beyond the float32 range overflow to Infinity
console.log('huge ->', Math.fround(3.5e38));