将逗号放在Javascript整数中

时间:2011-01-27 18:48:22

标签: javascript localization

所以我在Javascript中有一个值:

var val = Entry.val;

此值的一个示例是277385。我如何在Javascript中将此数字转换为277,385,以及任何数字,以便在正确的位置使用逗号?

4 个答案:

答案 0 :(得分:9)

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;
}

通过here

答案 1 :(得分:5)

这应该适合你:

<强>功能:

  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;
    }

用法:

addCommas(1000)
// 1,000

addCommas(1231.897243)
// 1,231.897243

感谢mredjk.com

答案 2 :(得分:2)

val.replace(/(\d{1,3})(?=(?:\d{3})+$)/g,"$1,")

: - )

答案 3 :(得分:1)

我不确定为什么其他答案会将小数点上的数字分开 - 您可以替换,从数字开始,直到没有更多数字。 它会在数字用完或点到非数字时退出。

function addCommas(n){
    var rx= /(\d+)(\d{3})/;
    return String(n).replace(/^\d+/, function(w){
        while(rx.test(w)) w= w.replace(rx,'$1,$2');
        return w;
    });
}