# 题目描述
请返回参数数字的千分位分隔符字符串。
# 测试用例
用例1:
- 输入:
_comma(12300)
- 输出:
'12,300'
# 代码实现
function _comma(number) {
// 补全代码
let numberStr = number.toString();
let len = numberStr.length;
if (len < 4) {
return number;
}
let cur = len - 3;
let res = "";
let temp = "";
let a = 0;
while (cur > 0) {
if (a == 0) {
res = numberStr.slice(0, cur) + "," + numberStr.slice(cur);
cur = cur - 3;
temp = res;
a++;
} else {
res = temp.slice(0, cur) + "," + temp.slice(cur);
cur -= 3;
temp = res;
}
}
return res;
}
// len = 7 cur = 4
// cur = 1
const res = _comma(1234567);
console.log("res: ", res);
// res: 1,234,567
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
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