分享几种有关金额的js方法:
1.数字金额转大写
1 function Chinese(num) { 2 if (!/^d*(.d*)?$/.test(num))throw(new Error(-1, "Number is wrong!")); 3 var AA = new Array("零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"); 4 var BB = new Array("", "拾", "佰", "仟", "萬", "億", "圆", ""); 5 var CC = new Array("角", "分", "厘"); 6 var a = ("" + num).replace(/(^0*)/g, "").split("."), k = 0, re = ""; 7 for (var i = a[0].length - 1; i >= 0; i--) { 8 switch (k) { 9 case 0 : 10 re = BB[7] + re; 11 break; 12 case 4 : 13 if (!new RegExp("0{4}\d{" + (a[0].length - i - 1) + "}$").test(a[0])) 14 re = BB[4] + re; 15 break; 16 case 8 : 17 re = BB[5] + re; 18 BB[7] = BB[5]; 19 k = 0; 20 break; 21 } 22 if (k % 4 == 2 && a[0].charAt(i) == "0" && a[0].charAt(i + 2) != "0") re = AA[0] + re; 23 if (a[0].charAt(i) != 0) re = AA[a[0].charAt(i)] + BB[k % 4] + re; 24 k++; 25 } 26 if (a[0].trim().charAt(0) == "") { // a = ["131321"] 27 re += AA[0]; 28 } 29 if (a.length > 1) { 30 re += BB[6]; 31 for (var i = 0; i < a[1].length; i++) { 32 re += AA[a[1].charAt(i)] + CC[i]; 33 if (i == 2) break; 34 } 35 if (a[1].charAt(0) == "0" && a[1].charAt(1) == "0") { 36 re += "元整"; 37 } 38 } else { 39 re += "元整"; 40 } 41 return re; 42 }
比如:
Chinese(123456789));// 壹億贰仟叁佰肆拾伍萬陆仟柒佰捌拾玖元整
2.数字转换为三位节 ,n---->小数点后保留的位数
1 function fmoney(s, n) { 2 n = n > 0 && n <= 20 ? n : 2; 3 s = parseFloat((s + "").replace(/[^d.-]/g, "")).toFixed(n) + ""; 4 var l = s.split(".")[0].split("").reverse(), 5 r = s.split(".")[1]; 6 t = ""; 7 for (i = 0; i < l.length; i++) { 8 t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : ""); 9 } 10 return t.split("").reverse().join("") + "." + r; 11 }
比如:
1 fmoney(1234567,2));//12 1,234,567.00 2 fmoney(1234567,3));//12 1,234,567.000