`

js经典实例 - 千分位符货币金额数据格式化(高级篇)

阅读更多

 

【实例代码】:

 

var Number = {
     /**
      * 格式化成金额形式
      *
      * @param num 数值(Number或者String)
      * @return 金额格式的字符串,如'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+)$"); //判断是否是浮点数 
        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;
   }
};

 

 

【测试代码】:

 

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

 

【打印结果】:

 

19,998,800
0
0
0
0

 

 

 

捐助分享者

          以前并不喜欢编程,但是现在已经是一个为程序而痴迷的IT迷,在此分享一些自己整理并优化后的东西,希望能给IT迷们有所帮助,有欣喜,也还有汗水,同时也希望大家能支持一下。 当然,有钱捧个钱场(支持支付宝和微信捐助,加入it资料中心扣扣群),没钱捧个人场,有了大家的支持,我们会更有动力,会做的更好的,谢谢各位。

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics