js classic example - thousands of currency amount data formatting (advanced)

 

[Example code]:

 

var Number =
     /**
      * formatted as amount
      *
      * @param num value (Number or String)
      * @return A string in amount format, such as '1,234,567.45'
      * @type String
      */
    formatAmount:function(num) {
    if(!num){
        return 0;
    }
    var num_top  = "";   
    var num_tail = "";
    var result = '';
    var re = new RegExp("^(-?\\d+)(\\.\\d+)$"); //Determine whether it is a floating point number
        if (re.test(num)){
           strSum = new String(num);
           if(strSum.indexOf(".") > -1) {                 
                 num_tail = strSum.split(".")[1];  
                 num_top = strSum.split(".")[0];
           }
           while (num_top.length > 3) {
               result = ',' + num_top.slice(-3) + result;
            num_top = num_top.slice(0, num_top.length - 3);
           }
           if (num_top) {
               result = num_top + result +'.'+ num_tail;
           }
         }else{
           num_top = new String(num);
           while (num_top.length > 3) {
               result = ',' + num_top.slice(-3) + result;
               num_top = num_top.slice(0, num_top.length - 3);
           }
           if (num_top) {
               result = num_top + result;
           }
         }
         return result;
   }
};

 

 

[Test code]:

 

console.info(Number.formatAmount(19998800));
console.info(Number.formatAmount());
console.info(Number.formatAmount(''));
console.info(Number.formatAmount(""));
console.info(Number.formatAmount(NaN));

 

【Print result】:

 

19,998,800
0
0
0
0

 

 

 

 

 

Donor sharer

          I didn't like programming before, but now I am an IT fan obsessed with programming. I would like to share some things I have sorted out and optimized here, hoping to help IT fans, with joy and sweat, and at the same time I also hope that everyone can support it. Of course, if you have money to support a money field (support Alipay and WeChat donations, join the it data center buckle group), but have no money to support a personal field, with your support, we will be more motivated and do better, thank you Ladies and gentlemen.

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326655647&siteId=291194637