Math.fround() 是 JavaScript 把數字轉成 32 位元單精度浮點數的靜態方法:傳入一個數字,回傳最接近它的 32 位元單精度浮點數表示值。
JavaScript 的數字內部都是 64 位元的倍精度浮點數(double-precision floating-point)。Math.fround() 的結果仍是一般數字,只是數值已經先被 32 位元的精度「削過」一遍。
語法
Math.fround(doubleFloat)
doubleFloat:一個數字。- 回傳值:最接近
doubleFloat的 32 位元單精度浮點數。
fround() 是 Math 的靜態方法,一律寫成 Math.fround(),不需要也不能 new Math()。
基本用法
console.log(Math.fround(5.5)); // 5.5
console.log(Math.fround(5.05)); // 5.050000190734863
console.log(Math.fround(5)); // 5
console.log(Math.fround(-5.05)); // -5.050000190734863
5.5 與 5 可以在二進位中精準表示,轉成 32 位元後不變。5.05 無法精準表示,所以轉換後出現誤差。
1.5 與 1.337 的差異
MDN 用兩個數字說明:1.5 可以在二進位中精準表示,在 32 位元與 64 位元下都一樣:
console.log(Math.fround(1.5)); // 1.5
console.log(Math.fround(1.5) === 1.5); // true
1.337 無法在二進位中精準表示,32 位元與 64 位元的結果不同:
console.log(Math.fround(1.337)); // 1.3370000123977661
console.log(Math.fround(1.337) === 1.337); // false
同樣的情形也發生在 0.1:
console.log(Math.fround(0.1)); // 0.10000000149011612
console.log(Math.fround(0.1) === 0.1); // false
超出範圍會變成 Infinity
數字超出 32 位元單精度浮點數能表示的範圍時,回傳 Infinity 或 -Infinity。MDN 的例子是 2 的 150 次方:
console.log(2 ** 150); // 1.42724769270596e+45
console.log(Math.fround(2 ** 150)); // Infinity
console.log(Math.fround(-(2 ** 150))); // -Infinity
整理成對照表:
| 輸入 | 結果 |
|---|---|
1.5 | 1.5 |
1.337 | 1.3370000123977661 |
0.1 | 0.10000000149011612 |
2 ** 150 | Infinity |
NaN | NaN |
與 Float32Array 搭配
MDN 提到,從 Float32Array 讀出數值時,容易混淆 64 位元與 32 位元的比較:兩個看起來一樣的數字,用 === 比較可能失敗。
const f32 = new Float32Array([1.337]);
console.log(f32[0]); // 1.3370000123977661
console.log(f32[0] === 1.337); // false
console.log(f32[0] === Math.fround(1.337)); // true
比較之前,先用 Math.fround() 把 64 位元的數字轉成 32 位元,兩邊就會一致。
捨入方式
依 MDN 的說明,Math.fround() 對尾數的第 23 位做「round to even」(捨入到偶數),再把後面的位元都設成 0。ECMAScript 規格也寫明是以 IEEE 754 的 binary32 格式、roundTiesToEven 模式轉換,再轉回 binary64。
JavaScript 內部仍把結果當成 64 位元浮點數處理,所以 Math.fround(0.1) 的結果是 0.10000000149011612,不是 0.1。
注意事項
- 結果仍是一般數字:
Math.fround()不會把數字變成 32 位元型別,只是讓數值等於某個 32 位元浮點數。 - 運算結果要再轉一次:兩個 32 位元的數字相加,結果以 64 位元計算,需要時再呼叫一次
Math.fround()。 - 超出範圍變 Infinity:輸入大小超過 32 位元能表示的範圍就會得到
Infinity或-Infinity。 - 精度依引擎而異:MDN 說明
Math的許多函式精度依實作而異,不同環境的結果最後幾位可能不同。
console.log(Math.fround(0.1) + Math.fround(0.2)); // 0.30000000447034836
console.log(Math.fround(Math.fround(0.1) + Math.fround(0.2))); // 0.30000001192092896
補充說明:範例輸出為 Node.js v22.20.0 的執行結果。相關方法還有
Math.round()。
發佈留言