// 字符串转换 1234567 > 1,234,567 function formatNum(s){ s = s.toString(); if (/[^0-9\.]/.test(s)){return "invalid value";} s = s.replace(/^(\d*)$/, "$1."); s = s.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"); s = s.substring(0, s.lastIndexOf(',')); return s } console.log(formatNum(1234567)) // 1,234,567 // 字符串转换 1234567 > ¥1,234,567.00 function formatNum(s){ s = s.toString(); if(/[^0-9\.]/.test(s)) return "invalid value"; s=s.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"); return "¥" + s.replace(/^\./,"0."); } console.log(formatNum(1234567)) // ¥1,234,567.00?
?