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

前端 未结 12 1838
灰色年华
灰色年华 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条回答
  •  -上瘾入骨i
    2020-12-02 17:32

    This will add thousand separators while retaining the decimal part of a given number:

    function format(n, sep, decimals) {
        sep = sep || "."; // Default to period as decimal separator
        decimals = decimals || 2; // Default to 2 decimals
    
        return n.toLocaleString().split(sep)[0]
            + sep
            + n.toFixed(decimals).split(sep)[1];
    }
    
    format(4567354.677623); // 4,567,354.68
    

    You could also probe for the locale's decimal separator with:

    var sep = (0).toFixed(1)[1];
    

提交回复
热议问题