用 js 把數字加千分位的方法

工作上的需要,記錄一下。

有許多種寫法,這個似乎是效能最好的寫法,參考的文章有測試各種寫法。
function toThousands(num) {
    var num = (num || 0).toString(), result = '';
    while (num.length > 3) {
        result = ',' + num.slice(-3) + result;
        num = num.slice(0, num.length - 3);
    }
    if (num) { result = num + result; }
    return result;
}

參考的文章有測試多種寫法,有興趣可以前往觀看其他種寫法及測試的效能數據。
从千分位格式化谈JS性能优化

留言