將數字轉為千分位字串(如 1234567 → "1,234,567")是常見需求。本文提供六種演算法,從直觀迴圈到正則替換,並附效能測試結果,幫助選擇最適合專案的方案。
function toThousands1(num) {
var result = [], counter = 0;
num = (num || 0).toString().split('');
for (var i = num.length - 1; i >= 0; i--) {
counter++;
result.unshift(num[i]);
if (counter % 3 === 0 && i !== 0) result.unshift(',');
}
return result.join('');
}
function toThousands2(num) {
var result = '', counter = 0;
num = (num || 0).toString();
for (var i = num.length - 1; i >= 0; i--) {
counter++;
result = num.charAt(i) + result;
if (counter % 3 === 0 && i !== 0) result = ',' + result;
}
return result;
}
function toThousands3(num) {
var str = (num || 0).toString(), re = /\d{3}$/, result = '';
while (re.test(str)) {
result = RegExp.lastMatch + result;
if (str !== RegExp.lastMatch) {
result = ',' + result;
str = RegExp.leftContext;
} else { str = ''; break; }
}
if (str) result = str + result;
return result;
}
function toThousands4(num) {
var str = (num || 0).toString(), result = '';
while (str.length > 3) {
result = ',' + str.slice(-3) + result;
str = str.slice(0, -3);
}
if (str) result = str + result;
return result;
}
function toThousands5(num) {
var str = (num || 0).toString(), mod = str.length % 3;
if (mod === 1) str = '00' + str;
else if (mod === 2) str = '0' + str;
return str.match(/\d{3}/g).join(',').replace(/^0+,?/, '');
}
function toThousands6(num) {
return (num || 0).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
正則解析:\B 非單字邊界,(?=(\d{3})+(?!\d)) 正向前瞻確保後方為 3 的倍數位數且非數字結尾。
| 數字 | 方法一 | 方法二 | 方法三 | 方法四 | 方法五 | 方法六 |
|---|---|---|---|---|---|---|
| 1 | 4 | 1 | 3 | 1 | 14 | 2 |
| 100 | 10 | 14 | 1 | 3 | 0 | 7 |
| 1000 | 12 | 1 | 2 | 4 | 5 | 3 |
| 10000 | 13 | 2 | 3 | 2 | 9 | 5 |
| 100000 | 21 | 4 | 3 | 1 | 6 | 3 |
| 1000000 | 21 | 3 | 2 | 1 | 5 | 6 |
Intl.NumberFormat:new Intl.NumberFormat('zh-TW').format(1234567.89); // "1,234,567.89"
Intl.NumberFormat 內建支援語系、貨幣、小數位等,效能優異且無需自行維護。