要在 JavaScript 中將數字四舍五入到小數點后兩位,請對數字調用 toFixed() 方法,即 num.toFixed(2)。toFixed() 會將數字四舍五入并將其格式化為小數點后兩位。
要在 JavaScript 中將數字四舍五入到小數點后兩位,請對數字調用 toFixed() 方法,即 num.toFixed(2)。toFixed() 會將數字四舍五入并將其格式化為小數點后兩位。

例如:
JavaScript
const num = 5.3281;
const result = num.toFixed(2);
console.log(result); // 5.33
const num2 = 3.1417
const result2 = num2.toFixed(2);
console.log(result2); // 3.14
toFixed() 方法采用數字 F 并返回小數點后 F 位數的數字的字符串表示形式。這里的 F 由傳遞給 toFixed() 的第一個參數 fractionDigits 參數決定。
const num = 5.3281;
console.log(num.toFixed(0)); // 5
console.log(num.toFixed(1)); // 5.3
console.log(num.toFixed(2)); // 5.33
console.log(num.toFixed(3)); // 5.328
console.log(num.toFixed(4)); // 5.3281
console.log(num.toFixed(5)); // 5.32810
將 toFixed() 的結果解析為數字。
請記住, toFixed() 返回一個字符串表示:
const num = 5.3281;
const result = num.toFixed(2);
console.log(result); // 5.33
console.log(typeof result); // string
但是,我們總是可以使用 Number() 構造函數將結果轉換為數字:
const num = 5.3281;
const result = Number(num.toFixed(2));
console.log(result); // 5.33
console.log(typeof result); // number
如果字符串有尾隨零,它們將在轉換中被刪除:
const num = 9.999999;
const strResult = num.toFixed(2);
const result = Number(strResult);
console.log(strResult); //10.00
console.log(result); // 10
小數點后的尾隨零不會改變數字的值,因此 10.00 與 10 或 10.00000000 相同。
console.log(10.00 === 10); // true
console.log(10.00000000 == 10); // true
將十進制字符串四舍五入到小數點后兩位。
有時輸入可能存儲為字符串。在這種情況下,我們首先需要使用 parseFloat() 函數將數字轉換為浮點數,然后再使用 toFixed() 將其四舍五入到小數點后兩位。
例如:
const numStr = '17.23593';
// ?? convert string to float with parseFloat()
const num = parseFloat(numStr);
const result = num.toFixed(2); // 17.24
console.log(result);
并非所有的十進制數都可以用二進制精確表示,因此在 JavaScript 的浮點數系統中存在一些舍入錯誤。例如:
console.log(44.85 * 0.1); // 4.485
console.log(45.85 * 0.1); // 4.585
console.log(46.85 * 0.1); // 4.6850000000000005 (?)
在此示例中,46.85 x 0.1 等于 4.6850000000000005,因為 46.85 無法用二進制浮點格式準確表示。
console.log((1.415).toFixed(2)); // 1.42
console.log((1.215).toFixed(2)); // 1.22
console.log((1.015).toFixed(2)); // 1.01 (?)
與第一個一樣,這里的 1.015 被四舍五入到小數點后兩位為 1.01 而不是 1.02,因為 1.015 在二進制數字系統中也無法準確表示。
此缺陷最常見的示例之一是經典的 0.1 + 0.2:
console.log(0.1 + 0.2 === 0.3); // false
console.log(0.1 + 0.2); // 0.30000000000000004
總結
以上就是我今天跟你分享的全部內容,希望這些小技巧小知識對你有用。