数据处理 | 数字按千分位隔开

实现效果

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];

// 处理整数部分
/*
注意添加逗号是从后面开始添加的
不然会出现这样的情况
123,456,7
这样是不对的,所以可以先翻转,处理完后再翻转
*/

let temp = [...n1].reverse(); // 转为['7', '6', '5','4', '3', '2','1']

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
}

// test
const num = 1234567.1234567;
console.log(fn(num)); // 1,234,567.1234567

方式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;
}

// test
const num = 1234567.1234567;
console.log(fn(num)); // 1,234,567.1234567