在 JavaScript 中有多种方法可以将数字保留两位小数,以下是几种常用的方法:
let num = 123.45678;
let result = num.toFixed(2); // "123.46" (返回的是字符串)
let numResult = parseFloat(num.toFixed(2)); // 123.46 (数字)
let num = 123.45678;
let result = Math.round(num * 100) / 100; // 123.46 (数字)
let num = 123.45678;
let result = Math.round((num + Number.EPSILON) * 100) / 100; // 123.46
let num = 123.45678;
let formatter = new Intl.NumberFormat('en-US', {
minimumFractionDigits: 2,
maximumFractionDigits: 2
});
let result = formatter.format(num); // "123.46" (字符串)
function roundToTwo(num) {
return +(Math.round(num + "e+2") + "e-2");
}
let result = roundToTwo(123.45678); // 123.46
浮点数运算可能存在精度问题,如 0.1 + 0.2 !== 0.3
对于货币计算等需要高精度的场景,建议使用专门的库如 decimal.js
toFixed()
会进行四舍五入,但有时会有意外的舍入结果
选择哪种方法取决于你的具体需求,如是否需要返回字符串或数字,是否需要考虑本地化等。