Adding comma as thousands separator (javascript) - output being deleted instead

前端 未结 5 973
你的背包
你的背包 2021-01-02 09:55

I am attempting to dynamically adjust a numerical value entered to include thousand separators

Here is my code:

function addCommas(nStr) {
    nStr +         


        
相关标签:
5条回答
  • 2021-01-02 10:36

    In each case before formatting try to remove existing commas first, like there: Removing commas in 'live' input fields in jquery

    Example:

    function addThousandsSeparator(x) {
        //remove commas
        retVal = x ? parseFloat(x.replace(/,/g, '')) : 0;
    
        //apply formatting
        return retVal.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }
    
    0 讨论(0)
  • 2021-01-02 10:49

    Try this regex:

    function numberWithCommas(x) {
      return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }
    
    0 讨论(0)
  • 2021-01-02 10:50

    as Dillon mentioned, it needs to be a string (or you could use typeof(n) and stringify if not)

    function addCommas(n){
        var s=n.split('.')[1];
        (s) ? s="."+s : s="";
        n=n.split('.')[0]
        while(n.length>3){
            s=","+n.substr(n.length-3,3)+s;
            n=n.substr(0,n.length-3)
        }
        return n+s
    }
    
    0 讨论(0)
  • 2021-01-02 10:51

    Try

    <input type="text" onkeyup="this.value=addCommas(this.value);" />
    

    instead. Since the function is working with text not numbers.

    0 讨论(0)
  • 2021-01-02 10:54

    To add the thousands separator you could string split, reverse, and replace calls like this:

    function addThousandsSeparator(input) {
        var output = input
        if (parseFloat(input)) {
            input = new String(input); // so you can perform string operations
            var parts = input.split("."); // remove the decimal part
            parts[0] = parts[0].split("").reverse().join("").replace(/(\d{3})(?!$)/g, "$1,").split("").reverse().join("");
            output = parts.join(".");
        }
    
        return output;
    }
    
    addThousandsSeparator("1234567890"); // returns 1,234,567,890
    addThousandsSeparator("12345678.90"); // returns 12,345,678.90
    
    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题