Math.round 默认会将数字四舍五入到最接近的整数。如果需要保留小数点后两位,可以通过以下方法实现:
方法 1:使用乘除法
- 将数字乘以 100,使其小数点后两位变为整数部分。
 - 使用 
Math.round四舍五入。 - 将结果除以 100,恢复小数点后两位。
 
const num = 3.14159;
const rounded = Math.round(num * 100) / 100;
console.log(rounded); // 3.14
方法 2:使用 toFixed 和 parseFloat
- 使用 
toFixed(2)将数字保留两位小数(返回字符串)。 - 使用 
parseFloat将字符串转换为数字。 
const num = 3.14159;
const rounded = parseFloat(num.toFixed(2));
console.log(rounded); // 3.14
方法 3:自定义函数
可以封装一个函数,方便重复使用:
function roundToTwoDecimals(num) { return Math.round(num * 100) / 100; } const num = 3.14159; console.log(roundToTwoDecimals(num)); // 3.14