Open unliar opened 3 years ago
const NumFormat = str => { // 切割小数 const arr = str.split("."); // 判断是否是负号 const isX = Number(arr[0]) > 0 ? false : true; // 替换掉负号符 const numStr = isX ? arr[0].replace("-", "") : arr[0]; // 反向 const numArr = numStr.split("").reverse(); // 结果集 let resArr = []; numArr.forEach((item, index) => { // 逢3补逗号 if (index > 0 && index % 3 === 0) { resArr.push(","); } resArr.push(item); }); resArr = resArr.reverse(); let resStr = resArr.join(""); // 补小数 if (arr[1]) { resStr = `${resStr}` + "." + arr[1]; } // 负数补负号 if (isX) { resStr = `-${resStr}`; } return `${resStr}`; };
正则表达式
const NumFormate = n => `${n}`.replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",")
正则表达式 const NumFormate = n => `${n}`.replace(/(\d)(?=(\d{3})+\.)/g,"$1,")
const NumFormate = n => `${n}`.replace(/(\d)(?=(\d{3})+\.)/g,"$1,")
only 111.111