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、字符串排序:倒序排列
// 字符串递归⽅法
js 正则替换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 += ',';
}
}
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));
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论