When we write shopping cart or place order and settlement page, we will calculate the total price of the goods and quantity selected by the user. The general practice is to toFixed(2) the total price and keep two decimal points behind, but in fact, this value is not accurate due to the historical problems of JS, so we want to use the toFixed method. You need to rewrite the native toFixed method as follows

Number.prototype.toFixed = function(n) { if (n > 20 || n < 0) { throw new RangeError("toFixed() digits argument must be between 0 and 20"); } const number = this; if (isNaN(number) || number >= Math.pow(10, 21)) { return number.toString(); } if (typeof n == "undefined" || n == 0) { return Math.round(number).toString(); } let result = number.toString(); const arr = result.split("."); If (arr.length < 2) {result += "."; for (let i = 0; i < n; i += 1) { result += "0"; } return result; } const integer = arr[0]; const decimal = arr[1]; if (decimal.length == n) { return result; } if (decimal.length < n) { for (let i = 0; i < n - decimal.length; i += 1) { result += "0"; } return result; } result = integer + "." + decimal.substr(0, n); const last = decimal.substr(n, 1); Const x = math.pow (10, n); if (parseInt(last, 10) >= 5) {const x = math.pow (10, n); result = (Math.round(parseFloat(result) * x) + 1) / x; result = result.toFixed(n); } return Number(result); };Copy the code

Just place the above code on a global functionality page, such as vue’s main.js, and if you’re worried, you can check the calculated value against the calculator