我怎样才能把逗号放在几千位?
how can i put commas in thousands?
`$.ajax({
url : "/selectList.do",
data:{memberNo:memberNo},
success : function(list){
console.log(list);
for(let i=0;i<list.length;i++){
list[i].NUMBER;
}
}
});`
我从 ajax 得到了数字,我想在这个数字中加上一个逗号(以千为单位)。
我该怎么做?
尝试使用 regex
const thousands = (o) => o.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ',');
console.log(thousands(123456789));
console.log(thousands(123456789.123));
或使用Number.prototype.toLocaleString()
const num = 123456.789;
console.log(num.toLocaleString());
const number = 123456.789;
const nf = new Intl.NumberFormat('en-US');
console.log(nf.format(number));
const insert = (arr, index, newItem) => [
...arr.slice(0, index),
newItem,
...arr.slice(index)
];
const thousands = (o) => {
let tmpArr = o.toString().split('.');
let splitArr = tmpArr[0].split('');
const reversed = splitArr.reverse();
for (let i = 1; i <= reversed.length; i++) {
if (i % 3 == 0)
splitArr = insert(splitArr, i, ',');
}
tmpArr[0] = tmpArr.length > 1 ? '.' : '';
return splitArr.reverse().concat(tmpArr).join('');
};
console.log(thousands(123456));
console.log(thousands(123456.789));
`$.ajax({
url : "/selectList.do",
data:{memberNo:memberNo},
success : function(list){
console.log(list);
for(let i=0;i<list.length;i++){
list[i].NUMBER;
}
}
});`
我从 ajax 得到了数字,我想在这个数字中加上一个逗号(以千为单位)。
我该怎么做?
尝试使用 regex
const thousands = (o) => o.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ',');
console.log(thousands(123456789));
console.log(thousands(123456789.123));
或使用Number.prototype.toLocaleString()
const num = 123456.789;
console.log(num.toLocaleString());
const number = 123456.789;
const nf = new Intl.NumberFormat('en-US');
console.log(nf.format(number));
const insert = (arr, index, newItem) => [
...arr.slice(0, index),
newItem,
...arr.slice(index)
];
const thousands = (o) => {
let tmpArr = o.toString().split('.');
let splitArr = tmpArr[0].split('');
const reversed = splitArr.reverse();
for (let i = 1; i <= reversed.length; i++) {
if (i % 3 == 0)
splitArr = insert(splitArr, i, ',');
}
tmpArr[0] = tmpArr.length > 1 ? '.' : '';
return splitArr.reverse().concat(tmpArr).join('');
};
console.log(thousands(123456));
console.log(thousands(123456.789));