最常用方法是使用toFixed(2)结合parseFloat或Number转换为数字,因toFixed返回字符串;对于精度要求高的场景,推荐使用Math.round(num * 100) / 100来避免浮点数误差;若需保留两位小数的格式化输出(如金额),可直接使用toFixed(2)保持字符串形式。

在 JavaScript 中实现四舍五入并保留两位小数,最常用的方法是使用 toFixed() 方法结合 parseFloat 或 Number 进行类型转换,因为 toFixed 返回的是字符串。
1. 使用 toFixed(2) 并转换为数字
toFixed(2) 会将数值保留两位小数,并进行四舍五入。但返回值是字符串,所以通常需要转回数字类型。
示例:let num = 3.14159; let result = parseFloat(num.toFixed(2)); console.log(result); // 3.14let num2 = 2.675; let result2 = Number(num2.toFixed(2)); console.log(result2); // 2.68(正确四舍五入)
2. 处理精度问题的更稳健方法
由于浮点数计算可能存在精度误差(如 0.1 + 0.2 !== 0.3),如果对精度要求高,可以借助数学运算来避免 toFixed 的潜在陷阱。
手动四舍五入函数:function roundToTwoDecimal(num) {
return Math.round(num * 100) / 100;
}
console.log(roundToTwoDecimal(3.14159)); // 3.14
console.log(roundToTwoDecimal(2.675)); // 2.68
3. 注意事项
直接使用 toFixed 可能在某些边界情况下显示异常(如返回 "3" 而不是 "3.00"),若需始终保留两位小数格式(如金额显示),可保持字符串形式。
保留格式输出:let price = 10; console.log(price.toFixed(2)); // "10.00"
基本上就这些。根据是否需要字符串格式或精确数值,选择 toFixed 配合类型转换,或用 Math.round 控制精度。










