When formatting numerical values, a common problem is to format according to the millites. There are already many solutions to this problem online. You can also use the Array.prototype.reduce method to achieve millite formatting.
function formatNumber(num) { if (isNaN(num)) { throw new TypeError("num is not a number"); } var groups = (/([/-/+]?)(/d*)(/./d+)?/g).exec("" + num), mask = groups[1], //sign bit integers = (groups[2] || "").split(""), // integer part decimal = groups[3] || "", // decimal part remains = integers.length % 3; var temp = integers.reduce(function(previousValue, currentValue, index) { if (index + 1 === remains || (index + 1 - remains) % 3 === 0) { return previousValue + currentValue + ","; } else { return previousValue + currentValue; } }, "").replace(//,$/g, ""); return mask + temp + decimal; }Array's reduce method is not supported below IE9, but we can implement a reduce method based on ECMAScript 3.
In JavaScript, the matching pattern parameter of the replace method of a string can be a regular expression in addition to a string. The following is the specific code to use the String.prototype.replace method to implement the formatting of the thousandthquare:
function formatNumber(num) { if (isNaN(num)) { throw new TypeError("num is not a number"); } return ("" + num).replace(/(/d{1,3})(?=(/d{3})+(?:$|/.))/g, "$1,"); }(/d{1,3}) is a capture group that can be referenced in reverse using $1. ?=(/d{3})+(?:$|/.) is a forward assertion, indicating that the match between 1 and 3 numbers must be followed by 3 numbers, but does not contain the last 3 numbers or 3 numbers and decimal points.
The two simple implementation methods for JavaScript numerical millite formatting in the above article are all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.