五种数字格式化方法 添加逗号 , 分割
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>五种数字格式化方法 添加逗号 , </title> </head> <body> <script type="text/javascript"> function f1(val) { let arrtemp = (val + '').split('.'); let strNew = '' function cf(val) { let s = '', ss = val.split('').reverse().join(''); for (let i = 0; i < ss.length; i++) { s += ss[i] if (i % 3 == 2 && i != ss.length - 1) { s += ',' } } str = s.split('').reverse().join('') return str; } if (arrtemp.length == 2) { if (arrtemp[0].length > 3) { strNew = cf(arrtemp[0]) + '.' + arrtemp[1] } else { strNew = arrtemp[0] + '.' + arrtemp[1] } } else { if (arrtemp[0].length > 3) { strNew = cf(arrtemp[0]) } else { strNew = arrtemp[0] } } return strNew; } function f2(val = 0) { let nerVal = '', valStr = (val + '').split('.'); function cf(val) { let arr = [], cnt = 0; for (let i = val.length - 1; i >= 0; i--) { cnt++; arr.unshift(val[i]); if (cnt % 3 == 0 && i != 0) { arr.unshift(','); } } return arr.join(''); } // val 带小数点 if (valStr.length == 2) { nerVal = cf(valStr[0]) + '.' + valStr[1] } else { nerVal = cf(valStr[0]) } return nerVal; } function f3(val = 0) { let nerVal = '', valStr = (val + '').split('.'); function cf(val) { let s = '', cnt = 0; for (let i = val.length - 1; i >= 0; i--) { cnt++; s = val.charAt(i) + s; if (cnt % 3 == 0 && i != 0) { s = ',' + s; } } return s; } // val 带小数点 if (valStr.length == 2) { nerVal = cf(valStr[0]) + '.' + valStr[1] } else { nerVal = cf(valStr[0]) } return nerVal; } function f4(val = 0) { let nerVal = '', valStr = (val + '').split('.'); function cf(val) { let s = '', cnt = 0; while (val.length > 3) { s = ',' + val.slice(-3); val = val.slice(0, val.length - 3) } if (val) { s = val + s; } return s; } // val 带小数点 if (valStr.length == 2) { nerVal = cf(valStr[0]) + '.' + valStr[1] } else { nerVal = cf(valStr[0]) } return nerVal; } function f5(val = 0) { let nerVal = '', valStr = (val + '').split('.'); function cf(val) { return val.replace(/(\d)(?=(?:\d{3})+$)/g, '$1,'); } // val 带小数点 if (valStr.length == 2) { nerVal = cf(valStr[0]) + '.' + valStr[1] } else { nerVal = cf(valStr[0]) } return nerVal; } console.log(f5(122255.3)) </script> </body> </html>
作者:孟繁贵 Email:meng010387@126.com 期待共同进步!