0%
实现效果
1 2 3 4 5 6 7 8
| const a = 1234567
const b = 1,234,567
const c = 1234567.1234567 const d = 1,234,567.1234567
|
手写实现
方式1:遍历添加
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| function fn(num) { let n = String(num).split('.'); let n1 = n[0], n2 = n[1];
let temp = [...n1].reverse(); let res = []; for (let index = 0; index < temp.length; index++) { if (index % 3 === 0 && index !== 0) { res.push(','); } res.push(temp[index]); } res.reverse(); let final = res.join(''); n2.length ? final = final + '.' + [...n2].join('') : final; return final }
const num = 1234567.1234567; console.log(fn(num));
|
方式2:正则表达式 replace 【正则表达式我表示记不住啊~】
1 2 3 4 5 6 7 8 9 10 11 12 13
| function fn(num) { let res=num.toString().replace(/\d+/, function(n){ return n.replace(/(\d)(?=(\d{3})+$)/g,function($1){ return $1+","; }); }) return res; }
const num = 1234567.1234567; console.log(fn(num));
|