Today, colleagues in the function of a need to use JS to implement a PHP function similar to number_format function, finally, the following method can be achieved:
/** * Number_format * @param number of numbers passed in, * @param bit reserved decimal places, default reserved two decimals, * @p Aram sign is an integer interval symbol, the default is a space * @param gapnum is an integer number of intervals, the default is 3 bits per * @type arguments function: arguments[0] = = Number (one) */ function Number_format (number,bit,sign,gapnum) {//Set the default value of the receive parameter var bit = arguments[1]? Arguments[1]: 2 ; var sign = arguments[2]? ARGUMENTS[2]: "; var gapnum = arguments[3]? ARGUMENTS[3]: 3; var str = '; Number = number.tofixed (bit);//Format realnum = Number.split ('. ') [0];//integer digits (using the decimal point to divide integers and fractional parts) decimal = Number.split ('. ') [1];//Decimal Realnumarr = Realnum.split (');//Place the integer digits bit by bit into the array ["1", "2", "3", "4", "5", "6"]//Set the integer part from right to left, each Bit bit adds a sign symbol For (var i=1;i<=realnumarr.length;i++) {str = realnumarr[realnumarr.length-i] + str; if (I%gapnum = = 0) {str = sign+str;//each gapnum bit preceded by a specified symbol}}//When a multiple of gapnum is encountered , such as ", 123", this situation, so to remove the front sign str = (realnum.length%gapnum==0)? STR.SUBSTR (1): str; Re-stitching real parts and decimal digits realnum = str+ '. ' +decimal; return realnum; }
Tested a bit:
$ ("#caonidaye"). Click (function () {
Console.log (Number_format (1234561.78,2, ', '));
})
Results:
JS implementation functions like PHP function Number_format