jQuery function to to format number with commas and decimal

后端 未结 2 1542
感情败类
感情败类 2020-12-16 16:07

I\'m using the following function to format numbers as the user types. It will insert a comma every 3 numbers. Ex: 45696.36 becomes 45,696.36.

相关标签:
2条回答
  • 2020-12-16 16:24

    You could accomplish this by splitting your string at the '.' character and then performing your comma-conversion on the first section only, as such:

    function ReplaceNumberWithCommas(yourNumber) {
        //Seperates the components of the number
        var n= yourNumber.toString().split(".");
        //Comma-fies the first part
        n[0] = n[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        //Combines the two sections
        return n.join(".");
    }
    
    ReplaceNumberWithCommas(1136.6696); //yields 1,136.6696
    

    Example

    0 讨论(0)
  • 2020-12-16 16:37

    I use accounting.js lib:

    accounting.format(1136.6696, 4) // 1,136.6696
    
    0 讨论(0)
提交回复
热议问题