添加逗号为千位分隔符(javascript) - 输出被删除

时间:2012-11-29 08:40:00

标签: javascript jquery

我试图动态调整输入的数值以包括千位分隔符

这是我的代码:

function addCommas(nStr) {
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}


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

然而,当我在4之后输入数字时,该字段被清除。

我出错的任何想法?如果有一个jQuery解决方案,我已经在我的网站上使用它了。

5 个答案:

答案 0 :(得分:14)

试试这个正则表达式:

function numberWithCommas(x) {
  return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

答案 1 :(得分:8)

要添加千位分隔符,您可以对这些调用进行字符串拆分,反向和替换:

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

答案 2 :(得分:5)

尝试

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

代替。由于该功能使用的是文本而不是数字。

答案 3 :(得分:2)

如Dillon所说,它需要是一个字符串(或者如果没有,你可以使用typeof(n)和stringify)

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
}

答案 4 :(得分:2)

在格式化之前的每种情况下,首先尝试删除现有的逗号,例如:Removing commas in 'live' input fields in jquery

示例:

function addThousandsSeparator(x) {
    //remove commas
    retVal = x ? parseFloat(x.replace(/,/g, '')) : 0;

    //apply formatting
    return retVal.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
相关问题