Use a regular expression to implement the sub-location separator. The regular expression is divided into thousands.
Original article, reproduced Please note: http://blog.csdn.net/chang_yuan_2011/article/details/46836045
The thousands separator is used to add a comma to a number every three digits. The idea is to determine whether there are more than four connected numbers in the number. If there are any, insert a comma between them, until four connected numbers are not found. Another point is that the split should start from the end. Convert the decimal point to a comma as the starting position of the entire search. After the entire number of sentences are split, the last comma is restored to the decimal point.
/*** User: YuanChang <yuanchang201344@gmail.com> * Date: 2015/7/10. * Time: 22:25 */function thousands (num) {num = num. toString (); // convert the input number to the string if (/^ -? \ D + \.? \ D + $/. test (num) {// determines whether the input content is an integer or a decimal if (/^ -? \ D + $ /. test (num) {// determines whether the input content is an integer num = num + ", 00"; // converts an integer to a decimal number with an accuracy of 2, replace the decimal point with a comma} else {num = num. replace (/\. /, ','); // Replace the decimal point with a comma} while (/\ d {4 }/. test (num) {// ***** determines whether there are 4 connected numbers. If yes, continue splitting; otherwise, end the loop; * divide four or more numbers connected to each other into two groups. The first group $1 indicates all the preceding numbers (negative numbers are signed). * The first group of the second group is a comma and the first three connected numbers; * Replace the second group with ", three connected numbers," ***/num = num. replace (/(\ d +) (\ d {3} \,)/, '$1, $ 2');} num = num. replace (/\, (\ d *) $ /,'. $ 1'); // Replace the last comma with the decimal point} // test thousands (-1); thousands (-100); thousands (-10000 ); thousands (-1000000); thousands (-1000.1); thousands (-1.001); thousands (-0.1); thousands (-0.001); thousands (1); thousands (100 ); thousands (10000); thousands (1000000); thousands (1.1); thousands (1.001); thousands (1000.1); thousands (0.001 );
Test results:
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.