4 kinds of digital thousand character formatting methods implemented by JS sharing _javascript Skills

Source: Internet
Author: User

The so-called digital thousand-digit form, that is, from single-digit digits, with a comma between each three digits. For example, "10,000". In response to this requirement, I initially wrote a function like this:

Copy Code code as follows:

Method One
function Tothousands (num) {
var result = [], counter = 0;
num = (num | | 0). toString (). Split (");
for (var i = num.length-1 i >= 0; i--) {
counter++;
Result.unshift (Num[i]);
if (!) ( Counter% 3) && I!= 0) {result.unshift (', ');}
}
Return Result.join (");
}

Method One is the process of converting numbers to strings, breaking an array, and then starting at the end, inserting the elements of the array into the beginning of the new Array (result). Each time you insert an element, counter counts (plus 1), and when counter is a multiple of 3, you insert a comma, but note that the beginning (i is 0 o'clock) does not require a comma. Finally, the result is obtained by calling the join method of the new array.

Method A more clear and understandable, but also in the project for some time. But my gut tells me that it's not very good at performance.

Method Two--a string version of method one

Copy Code code as follows:

Method Two
function Tothousands (num) {
var result = ', counter = 0;
num = (num | | 0). toString ();
for (var i = num.length-1 i >= 0; i--) {
counter++;
result = Num.charat (i) + result;
if (!) ( Counter% 3) && I!= 0) {result = ', ' + result;}
}
return result;
}

Method Two is an improved version of method one, which does not break strings into arrays, and always operates on strings.

Method three--loops match three digits at end

Copy Code code as follows:

Method Three
function Tothousands (num) {
var num = (num | | 0). toString (), re =/\d{3}$/, result = ';
while (Re.test (num)) {
result = Regexp.lastmatch + result;
if (num!== regexp.lastmatch) {
result = ', ' + result;
num = Regexp.leftcontext;
} else {
num = ';
Break
}
}
if (num) {result = num + result;}
return result;
}

Method Three is a completely different algorithm, the regular expression loop to match the end of the three digits, each match, the comma and match to the content inserted into the beginning of the result string, and then the matching target (NUM) assigned to the content is not matched (regexp.leftcontext). In addition, note:

1. If the number of digits is a multiple of 3, the last match to the content must be three digits, but the first three digits before the need to add a comma;
2. If the number of digits is not a multiple of 3, the NUM variable will eventually be left with 1 to 2 digits, after the loop, to insert the remaining digits to the beginning of the result string.

Although method three reduces the number of cycles (three characters at a time), it increases consumption to some extent because of the use of regular expressions.

Method four--string version of method three

Copy Code code as follows:

Method Four
function Tothousands (num) {
var num = (num | | 0). toString (), result = ';
while (Num.length > 3) {
result = ', ' + num.slice ( -3) + result;
num = Num.slice (0, num.length-3);
}
if (num) {result = num + result;}
return result;
}

In fact, the function of intercepting the three characters at the end can be done through the slice, substr, or substring method of the string type. This avoids the use of regular expressions.

Method Five--group merging method

Copy Code code as follows:

Method Five
function Tothousands (num) {
var num = (num | | 0). toString (), temp = num.length% 3;
Switch (temp) {
Case 1:
num = ' + ' + num;
Break
Case 2:
num = ' 0 ' + num;
Break
}
Return Num.match (/\d{3}/g). Join (', '). Replace (/^0+/, ");
}

First, the number of digits to make up a multiple of 3, through the regular expression, cut it into a group of three digits, and then add a comma through the Join method, and finally to the completion of the 0 removed.

Method Six--Lazy person method

Copy Code code as follows:

Method Six
function Tothousands (num) {
return (num | | 0). toString (). Replace (/(\d) (? = (?: \ D{3}) +$)/g, ' $, ');
}

Always feel that this format can be done through a regular expression replacement, but need to use the assertion and so on, but I do not too familiar with this part. Google a bit, and really found such a regular expression, which is estimated to be the shortest code implementation.

Test results

Digital 5,000 times of consumption performed (MS)
Method One Method Two Method Three method Four Method Five Method Six
1 4 1 3 1 14 2
10 14 1 3 0 7 2
100 12 1 2 4 5 3
1000 13 2 3 2 9 5
10000 21st 4 3 1 6 3
100000 21st 3 2 1 5 6

The strong contrast between method one and method two shows that the efficiency of string manipulation is much higher than that of array operations; method Six test results tell us that the length of the code is not related to the level of performance. The overall performance of method four is the best (but why NUM is 100, it does not work, this is really puzzling), mainly because:

1. Comparison method one or two, each operation 3 characters instead of 1 characters, reduce the number of cycles;
2. The comparison method is three, five or six, does not use the regular expression, reduces consumes.

Finally, I chose method Four as the final optimization scheme. Readers can comment if they have a better way to implement or improve their views.

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.