js格式化数字,金额按千位逗号分隔,负号用括号

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

 

你可能感兴趣的:(js格式化数字,金额按千位逗号分隔,负号用括号)