方式一: 算法实现
function getThousand (numStr) {
if (numStr.length < 4) return numStr;
let len = numStr.length;
let restLen = len % 3;
let arr = [];
let num = 3;
for(var i=0; i<len;) {
if (restLen !== 0 && i === 0) {
arr.push(numStr.slice(i, i + restLen));
i += restLen;
} else {
arr.push(numStr.slice(i, i + num));
i += num;
}
}
return arr.join(',');
}
function ensureEqual(a, b, message) {
if (JSON.stringify(a) !== JSON.stringify(b)) {
console.log(`***测试失败, ${JSON.stringify(a)} 不等于 ${JSON.stringify(b)}, ${message}`);
}
};
ensureEqual(getThousand('999'), '999', 'test1');
ensureEqual(getThousand('1000'), '1,000', 'test2');
ensureEqual(getThousand('100000'), '100,000', 'test3');
ensureEqual(getThousand('1000000'), '1,000,000', 'test4');
如果需要支持小数的话,那么把小数部分 split 一下即可
方式二: 使用正则表达式
function _getThousand (num) {
return num.toString().replace(/B(?=(d{3})+$)/g, ',');
}
ensureEqual(_getThousand('999'), '999', 'test1');
ensureEqual(_getThousand('1000'), '1,000', 'test2');
ensureEqual(_getThousand('100000'), '100,000', 'test3');
ensureEqual(_getThousand('1000000'), '1,000,000', 'test4');