0

Possible Duplicate:
how to print number with commas as thousands separators in Javascript

I have found a few posts along these lines but none of them provide the solution i'm looking for. I have a number variable that is being output to a page using document.write.

I need to comma separate this value, is there an efficient way to insert a comma after every third number (ex: 256012 to 256,012).

Here is my js in full:

//vars declared (located top of page)<br />
var miles = 256012;//miles completed<br />
var progress =  (miles / 477714) * 100;

//output var (into page content)<br />
<script>document.write (miles);</script> Miles Complete

//adjust width of progress bar according to % complete (bottom scripts)<br />
function rtmProgressBar (ObjectID, Value){<br />
        document.getElementById(ObjectID).style.width =  Value.toString() + "%";<br />
    }<br />
    rtmProgressBar("rtm-progress-wrap", progress);

Any insight would be greatly appreciated.

4

2 回答 2

1

这是我使用的一个:

var addCommas = function (nStr) {
    nStr += '';
    var x = nStr.split('.');
    var x1 = x[0];
    var x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
      x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}
于 2011-10-13T16:02:01.907 回答
0

你可以使用这个,我刚刚在我最新的 actionscript 项目中使用了这个。正则表达式的伟大之处在于它们在大多数编程语言之间是通用的。

var commaFormat = function(string)
{
    return string = string.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
}
于 2011-10-13T16:06:46.873 回答