Original articles, reproduced please specify: http://blog.csdn.net/chang_yuan_2011/article/details/46836045
The thousand separator is the number, every three digits into a comma, the idea is to determine whether there are more than four connected numbers in the number, if there is a comma in between them, until the four connected numbers can not be found. The other point is that the split should start at the end of the tail. At the beginning, the decimal point is converted to a comma as the starting position of the entire search, and the entire number of sentences is divided and the last comma is restored to a decimal point.
/** * user:yuanchang<yuanchang201344@gmail.com> * date:2015/7/10. * time:22:25 * *function thousands (num) {num = num.tostring ();//Converts the input number to a string if(/^-?\d+\.? \d+$/.test (num)) {//Determine if the input is an integer or decimal if(/^-?\d+$/.test (num)) {//Determine if the input is an integerNum =num +", xx";//Convert an integer to a decimal with a precision of 2 and change the decimal point to a comma}Else{num = Num.replace (/\./,', ');//Convert decimal point to comma} while(/\d{4}/.test (num)) {// /*** * To determine if there are 4 connected numbers, if there is a need to continue to split, otherwise end the loop; * Divide 4 connected numbers into two groups, the first set is all previous numbers (negative numbers are signed), and the second group A comma and its preceding 3 concatenated numbers; * Replace the second set of contents with ", 3 connected numbers," ***/num = Num.replace (/(\d+) (\d{3}\,)/,' $1,$2 '); num = Num.replace (/\, (\d*) $/,'. $ ');//Change the last comma to decimal points}}//TestThousands (-1); Thousands (- -); Thousands (-10000); Thousands (-1000000); Thousands (-1000.1); Thousands (-1.001); Thousands (-0.1); Thousands (-0.001); thousands (1); thousands ( -); thousands (10000); thousands (1000000); thousands (1.1); thousands (1.001); thousands (1000.1); thousands (0.001);
Test results:
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Implementing a thousand-bit delimiter with regular expressions