js中数字加逗号处理(每三位加逗号)?前⾔,⾯试中遇到将数字增加“,”,⽅便区分位数,这⾥记录⼀下,以便后续⽤到
1、正则表达式:正则替换
// 正则表达式
const toThousands = (num = 0) => {
String().replace(/\d+/, function(n) {
place(/(\d)(?=(?:\d{3})+$)/g, '$1,');
});
};
console.log(toThousands(1234567890.111)); //1,234,567,890.111
2、字符串排序:倒序排列
// 字符串递归⽅法
const toThousands = (num = 0) => {
let result = '';
let numArr = String().split('.');
let int = numArr[0];
let decmial = numArr[1] ? '.' + numArr[1] : '';
for (let n = int.length - 1; n >= 0; n--) {
result += int[int.length - n - 1];
if ((int.length - n - 1) % 3 === 0 && n !== 0) {
result += ',';
}js正则表达式判断数字
}
return result + decmial;
};
console.log(toThousands(1234567890.111)); //1,234,567,890.111
3、字符串模板:使⽤slice不断截取,不断分割
function toThousands(num = 0) {
let result = '';
let numArr = String().split('.');
let int = numArr[0];
let decmial = numArr[1] ? '.' + numArr[1] : '';
while (int.length > 3) {
result = ',' + int.slice(-3) + result;
int = int.slice(0, int.length - 3);
}
if (int) {
result = int + result;
}
return result + decmial;
}
console.log(toThousands(1234567890.111));
综上所述,计算所耗时间,可见⼀个问题代码短不⼀定性能就好,推荐使⽤第⼆种⽅法
⽅法⼀⽅法⼆⽅法三
1.8220.1040.118