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

前端 未结 12 1886
灰色年华
灰色年华 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:34

    This is how I do it:

    // 2056776401.50 = 2,056,776,401.50
    function humanizeNumber(n) {
      n = n.toString()
      while (true) {
        var n2 = n.replace(/(\d)(\d{3})($|,|\.)/g, '$1,$2$3')
        if (n == n2) break
        n = n2
      }
      return n
    }
    

    Or, in CoffeeScript:

    # 2056776401.50 = 2,056,776,401.50
    humanizeNumber = (n) ->
      n = n.toString()
      while true
        n2 = n.replace /(\d)(\d{3})($|,|\.)/g, '$1,$2$3'
        if n == n2 then break else n = n2
      n
    

提交回复
热议问题