要在 JavaScript 中將數(shù)字四舍五入到小數(shù)點(diǎn)后兩位,請(qǐng)對(duì)數(shù)字調(diào)用 toFixed() 方法,即 num.toFixed(2)。toFixed() 會(huì)將數(shù)字四舍五入并將其格式化為小數(shù)點(diǎn)后兩位。
要在 JavaScript 中將數(shù)字四舍五入到小數(shù)點(diǎn)后兩位,請(qǐng)對(duì)數(shù)字調(diào)用 toFixed() 方法,即 num.toFixed(2)。toFixed() 會(huì)將數(shù)字四舍五入并將其格式化為小數(shù)點(diǎn)后兩位。

例如:
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() 方法采用數(shù)字 F 并返回小數(shù)點(diǎn)后 F 位數(shù)的數(shù)字的字符串表示形式。這里的 F 由傳遞給 toFixed() 的第一個(gè)參數(shù) fractionDigits 參數(shù)決定。
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() 的結(jié)果解析為數(shù)字。
請(qǐng)記住, toFixed() 返回一個(gè)字符串表示:
const num = 5.3281;
const result = num.toFixed(2);
console.log(result); // 5.33
console.log(typeof result); // string
但是,我們總是可以使用 Number() 構(gòu)造函數(shù)將結(jié)果轉(zhuǎn)換為數(shù)字:
const num = 5.3281;
const result = Number(num.toFixed(2));
console.log(result); // 5.33
console.log(typeof result); // number
如果字符串有尾隨零,它們將在轉(zhuǎn)換中被刪除:
const num = 9.999999;
const strResult = num.toFixed(2);
const result = Number(strResult);
console.log(strResult); //10.00
console.log(result); // 10
小數(shù)點(diǎn)后的尾隨零不會(huì)改變數(shù)字的值,因此 10.00 與 10 或 10.00000000 相同。
console.log(10.00 === 10); // true
console.log(10.00000000 == 10); // true
將十進(jìn)制字符串四舍五入到小數(shù)點(diǎn)后兩位。
有時(shí)輸入可能存儲(chǔ)為字符串。在這種情況下,我們首先需要使用 parseFloat() 函數(shù)將數(shù)字轉(zhuǎn)換為浮點(diǎn)數(shù),然后再使用 toFixed() 將其四舍五入到小數(shù)點(diǎn)后兩位。
例如:
const numStr = '17.23593';
// ?? convert string to float with parseFloat()
const num = parseFloat(numStr);
const result = num.toFixed(2); // 17.24
console.log(result);
并非所有的十進(jìn)制數(shù)都可以用二進(jìn)制精確表示,因此在 JavaScript 的浮點(diǎn)數(shù)系統(tǒng)中存在一些舍入錯(cuò)誤。例如:
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,因?yàn)?46.85 無(wú)法用二進(jìn)制浮點(diǎn)格式準(zhǔn)確表示。
console.log((1.415).toFixed(2)); // 1.42
console.log((1.215).toFixed(2)); // 1.22
console.log((1.015).toFixed(2)); // 1.01 (?)
與第一個(gè)一樣,這里的 1.015 被四舍五入到小數(shù)點(diǎn)后兩位為 1.01 而不是 1.02,因?yàn)?1.015 在二進(jìn)制數(shù)字系統(tǒng)中也無(wú)法準(zhǔn)確表示。
此缺陷最常見的示例之一是經(jīng)典的 0.1 + 0.2:
console.log(0.1 + 0.2 === 0.3); // false
console.log(0.1 + 0.2); // 0.30000000000000004
總結(jié)
以上就是我今天跟你分享的全部?jī)?nèi)容,希望這些小技巧小知識(shí)對(duì)你有用。