Add a thousands separator to a total with Javascript or jQuery?

前端 未结 12 1894
灰色年华
灰色年华 2020-12-02 16:48

I have a function that sums a column of data in an html table. It does so admirably only I would like to have it put the commas in there that are needed to separate the thou

12条回答
  •  悲哀的现实
    2020-12-02 17:27

    a recursive solution:

    function thousands(amount) {
      if( /\d{3}\d+/.test(amount) ) {
        return thousands(amount.replace(/(\d{3}?)(,|$)/, ',$&'));
      }
      return amount;
    }
    

    another split solution:

    function thousands (amount) {
      return amount
        // reverse string
        .split('')
        .reverse()
        .join('')
        // grouping starting by units
        .replace(/\d{3}/g, '$&,')
        // reverse string again
        .split('')
        .reverse()
        .join('');
    }
    

提交回复
热议问题