functionformatMoney(s, type) { if (/[^0-9\.]/.test(s)) return"0"; if (s == null || s == "") return"0"; s = s.toString().replace(/^(\d*)$/, "$1."); s = (s + "00").replace(/(\d*\.\d\d)\d*/, "$1"); s = s.replace(".", ","); var re = /(\d)(\d{3},)/; while (re.test(s)) s = s.replace(re, "$1,$2"); s = s.replace(/,(\d\d)$/, ".$1"); if (type == 0) {// 不带小数位(默认是有小数位) var a = s.split("."); if (a[1] == "00") { s = a[0]; } } return s; } formatMoney('13222222',3)
二、字符串正则处理
1 2 3 4 5 6 7 8
functionformat_number(n){ var b=parseInt(n).toString(); var len=b.length; if(len<=3){return b;} var r=len%3; return r>0?b.slice(0,r)+","+b.slice(r,len).match(/\d{3}/g).join(","):b.slice(r,len).match(/\d{3}/g).join(","); } format_number('4524324234');
三、正则表达式
1 2 3 4 5 6 7 8
var num='12345678'; var str = num.replace(/\d(?=(?:\d{3})+\b)/g,'$&,'); console.log(str); //"12,345,678"