以下是几种常见的方法:
- 使用 Number.prototype.toFixed() 方法,该方法返回一个字符串,其表示 Number 对象的指定精度(小数点后位数)的数字,四舍五入。
let num = 3.1415926; console.log(num.toFixed(2)); // 输出 "3.14"
- 使用 Math.round() 方法,将小数乘以 100 后四舍五入,再除以 100。
let num = 3.1415926; console.log(Math.round(num * 100) / 100); // 输出 "3.14"
- 使用 parseFloat() 和 toFixed() 方法结合。
let num = "3.1415926"; console.log(parseFloat(num).toFixed(2)); // 输出 "3.14"
这些方法都可以将数字保留两位小数。