JS implementation functions like PHP function Number_format

Source: Internet
Author: User

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

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.