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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM