js格式化数字 金额按千位逗号分隔

 1 // 返回数字
 2 function removeFormatMoney(s) {
 3     return parseFloat(s.replace(/[^\d\.-]/g, ""));
 4 }
 5 
 6 /* 
 7  * formatMoney(s,type) 
 8  * 功能:金额按千位逗号分隔
 9  * 参数:s,需要格式化的金额数值. 
10  * 参数:type,判断格式化后的金额是否需要小数位. 
11  * 返回:返回格式化后的数值字符串. 
12  */ 
13 function formatMoney(s, type) {
14     if (/[^0-9\.]/.test(s))
15         return "0.00";
16     if (s == null || s == "null" || s == "")
17         return "0.00";
18     s = s.toString().replace(/^(\d*)$/, "$1.");
19     s = (s + "00").replace(/(\d*\.\d\d)\d*/, "$1");
20     s = s.replace(".", ",");
21     var re = /(\d)(\d{3},)/;
22     while (re.test(s))
23         s = s.replace(re, "$1,$2");
24     s = s.replace(/,(\d\d)$/, ".$1");
25     if (type == 0) {
26         var a = s.split(".");
27         if (a[1] == "00") {
28             s = a[0];
29         }
30     }
31     return s;
32 }

转载:http://blog.csdn.net/evangel_z/article/details/12839657

posted @ 2016-03-02 08:37  fanhq  阅读(8700)  评论(1编辑  收藏  举报