In the format of the value of the time, a common problem is in accordance with the format of thousands of bits, there are many ways to solve the problem on the Internet, you can also use the Array.prototype.reduce method to achieve the format of thousands of bits.
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 (""),//integral part decimal = Groups[3] | | "", //Fractional part remain = integers.length% 3;var temp = integers.reduce (function (pre Viousvalue, CurrentValue, index) {if (index + 1 = = = Remain | | (index + 1-remain)% 3 = = = 0) {return previousvalue + CurrentValue + ",";} else {return previousvalue + CurrentValue;}} , ""). Replace (/\,$/g, ""); return mask + temp + decimal;}
The reduce method of array is not supported below IE9, however, we can implement a reduce method based on ECMAScript three, refer to the MDN on the Array.prototype.reduce method of introduction.
In JavaScript, the match-mode parameter of the Replace method of a string can be a regular expression in addition to the string, and the following is the specific code that uses the String.prototype.replace method to format the thousands of bits:
function FormatNumber (num) {if (IsNaN (num)) {throw new TypeError ("num is not a number");} Return ("" + num). Replace (/(\d{1,3}) (? = (\d{3}) + (?: $|\.)) /g, "$,"); }
(\d{1,3}) is a capture grouping that can be reversed with $ $,? = (\d{3}) + (?: $|\.) is a forward assertion, which indicates that a match of 1 to 3 digits must follow 3 digits, but does not contain the last 3 digits or 3 digits and decimal points.
Two ways to format JavaScript numeric thousand bits