最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

localization - Place commas in Javascript integers - Stack Overflow

programmeradmin3浏览0评论

So I have a value in Javascript:

var val = Entry.val;

One example of this value is 277385. How do I, in Javascript, convert this number to 277,385, as well as any number to that so it has mas in the correct spots?

So I have a value in Javascript:

var val = Entry.val;

One example of this value is 277385. How do I, in Javascript, convert this number to 277,385, as well as any number to that so it has mas in the correct spots?

Share Improve this question edited Jan 27, 2011 at 18:51 David Wolever 155k93 gold badges362 silver badges510 bronze badges asked Jan 27, 2011 at 18:48 slandauslandau 24.1k43 gold badges124 silver badges186 bronze badges 0
Add a ment  | 

4 Answers 4

Reset to default 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;
}

via here.

This should do it for you:

Function:

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

Usage:

addCommas(1000)
// 1,000

addCommas(1231.897243)
// 1,231.897243

Thanks to mredjk.

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

:-)

I'm not sure why the other answers split the number on a decimal point- you can replace, starting with a digit,until there are no more digits. It will quit when it runs out of digits or hits a non-digit.

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;
    });
}
发布评论

评论列表(0)

  1. 暂无评论