[Javascript]數字加上逗號comma(浮點數也可用)

  • 2754
  • 0
  • 2022-10-26

摘要:[Javascript]數字加上逗號comma(浮點數也可用)

參考http://www.mredkj.com,非常感謝!

怕以後對方資料刪掉,自己備份一下

他是用Regular expression寫的,清楚明瞭

從這個寫法 x1 = x1.replace(rgx, '$1' + ',' + '$2');來看的話

他的regular expresstion的parser方式應該都是

每次都從最左邊一口氣讀取到最右邊的位數

然後一步一步地往回推,回推的過程要是符合pattern

就做replace的動作

function addCommas(nStr) {
    nStr += '';

    //如果addCommas()事件是加在change
    //下面這行就維持在註解狀態
    //如果是加在keyup事件
    //就把註解拿掉
    //nStr = nStr.replaceAll(',', '');
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}