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.

Community
  • 1
  • 1
user993828
  • 19
  • 2

2 Answers2

1

Here's the one I use:

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;
}
Joe
  • 77,580
  • 18
  • 124
  • 143
0

You can use this, I just used this on my latest actionscript project. The great thing about regular expressions is that they are universal between most programming languages.

var commaFormat = function(string)
{
    return string = string.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
}
brenjt
  • 15,581
  • 13
  • 78
  • 116