数字千分位
题目
将数字按照千分位生成字符串,即每三位加一个逗号。不考虑小数。
如输入数字 78100200300 返回字符串 '78,100,200,300'
分析
- 使用数组
- 使用正则表达式
- 使用字符串拆分
性能分析
- 数组转换,影响性能
- 正则表达式,性能较差
- 操作字符串,性能较好
/**
* 千分位格式化(使用数组)
* @param n number
*/
function formatNum1(n) {
n = Math.floor(n);
const s = n.toString();
const arr = s.split('').reverse();
return arr.reduce((prev, val, index) => {
if (index % 3 === 0) {
if (prev) {
return `${val},${prev}`;
} else {
return val;
}
} else {
return val + prev;
}
}, '');
}
/**
* 数字千分位格式化(字符串分析)
* @param n number
*/
function formatNum2(n) {
n = Math.floor(n);
const s = n.toString();
const length = s.length;
let res = '';
for (let i = length - 1; i >= 0; i--) {
const j = length - i;
if (j % 3 === 0) {
if (i === 0) {
res = s[i] + res;
} else {
res = `,${s[i]}${res}`;
}
} else {
res = s[i] + res;
}
}
return res;
}