Two ways to format JavaScript numeric thousand bits

Source: Internet
Author: User

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

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.