js中针对toFixed 的精度调整
1 /* eslint-disable-next-line */ 2 Number.prototype.toFixed = function(d) { 3 let s = `${this}` 4 /* eslint-disable-next-line */ 5 if (!d) d = 0 6 if (s.indexOf(".") === -1) s += "." 7 s += new Array(d + 1).join("0") 8 if (new RegExp(`^(-|\\+)?(\\d+(\\.\\d{0,${d + 1}})?)\\d*$`).test(s)) { 9 s = `0${RegExp.$2}` 10 const pm = RegExp.$1 11 let a = RegExp.$3.length 12 let b = true 13 if (a === d + 2) { 14 a = s.match(/\d/g) 15 if (parseInt(a[a.length - 1], 10) > 4) { 16 for (let i = a.length - 2; i >= 0; i--) { 17 a[i] = parseInt(a[i], 10) + 1 18 if (a[i] === 10) { 19 a[i] = 0 20 b = i !== 1 21 } else break 22 } 23 } 24 s = a.join("").replace(new RegExp(`(\\d+)(\\d{${d}})\\d$`), "$1.$2") 25 } 26 if (b) s = s.substr(1) 27 return (pm + s).replace(/\.$/, "") 28 } 29 return `${this}` 30 }