1. toFixed是四舍五入保留两位小数
精度问题导致:toFixed 四舍五入结果不准确,比如 1.335.toFixed(2) == 1.33
2. 实现截取两位小数方案
- 正则匹配
// 截取 N位小数(直接丢弃指定位数之后的);
Number.prototype.cutFixed = function(digit = 2) {
let reg = new RegExp(`^\\d+(?:\\.\\d{0,${digit}})?`);
return Number(this.toString().match(reg));
};
(9.9999).cutFixed(2) => 9.99
- 使用Math.floot(num * 100)/100
⚠️ 此方案中,Math.floor()容易出现精度问题
Math.floor(8.54*100)/100 => 8.53
- 字符串操作。同正则