4

I'm using the following script to count upward at an interval and it works perfectly. However, I'd like it to format the number with commas (56,181,995 instead of 56181995).

var START_DATE = new Date("July 27, 2010 13:30:00"); // put in the starting date here
var INTERVAL = 1; // in seconds
var INCREMENT = 2; // increase per tick
var START_VALUE = 101; // initial value when it's the start date
var count = 0;

window.onload = function()
{
var msInterval = INTERVAL * 1000;
var now = new Date();
count = parseInt((now - START_DATE)/msInterval) * INCREMENT + START_VALUE;
document.getElementById('counter').innerHTML = count;
setInterval("count += INCREMENT; document.getElementById('counter').innerHTML = count;", msInterval);
}

I thought I had found an answer here on SO but I can't get it to work:

How to print a number with commas as thousands separators in JavaScript

Community
  • 1
  • 1
brianrhea
  • 3,674
  • 3
  • 34
  • 57

4 Answers4

18
(1234567890).toLocaleString();
James
  • 20,957
  • 5
  • 26
  • 41
  • [According to MDN](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString#Browser_compatibility), calling `.toLocaleString` without any arguments is supported across all browsers. – Walter Roman Mar 09 '15 at 04:15
  • Thank you for this answer, was looking for something native and simple – Osinachi Feb 24 '21 at 16:50
12
function addCommas(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;
}

http://www.mredkj.com/javascript/nfbasic.html

To integrate:

var msInterval = INTERVAL * 1000;
var now = new Date();
count = parseInt((now - START_DATE)/msInterval) * INCREMENT + START_VALUE;
document.getElementById('counter').innerHTML = addCommas(count);
setInterval("count += INCREMENT; document.getElementById('counter').innerHTML = addCommas(count);", msInterval);
Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
  • How do I integrate this with the function I'm using? – brianrhea Jun 17 '11 at 21:49
  • 1
    I don't know whether you noticed, but this function implicitly declares `x`, `x1`, and `x2` in the global namespace. I only discovered this because I found someone had added this function in *our* codebase verbatim, and went looking for the source. No downvote, because it's slapdash sample code, but I think you ought to fix it for future C&P jockeys. – Robusto Oct 09 '13 at 12:54
2

formatting - How can I format numbers as money in JavaScript?

using this SO post on formatting money as a basis, you can re-engineer this to work for just comma separation

here's an example - http://jsfiddle.net/pxfunc/etfjW/

You can extend the javascript Number type to include a commaSeparated formatter method like so:

Number.prototype.commaSeparated = function() {
    var n = this,
        t = ",",
        s = n < 0 ? "-" : "",
        i = parseInt(n = Math.abs(+n || 0)) + "",
        j = (j = i.length) > 3 ? j % 3 : 0;
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t);
};

then call it like so

count.commaSeparated();

or

(1234567890).commaSeparated();
Community
  • 1
  • 1
MikeM
  • 27,227
  • 4
  • 64
  • 80
2
function addCommas(str){
   var arr,int,dec;
   str += '';

   arr = str.split('.');
   int = arr[0] + '';
   dec = arr.length>1?'.'+arr[1]:'';

   return int.replace(/(\d)(?=(\d{3})+$)/g,"$1,") + dec;
}
Gordon Tucker
  • 6,653
  • 3
  • 27
  • 41
vol7ron
  • 40,809
  • 21
  • 119
  • 172
  • Thx for editing Gordon, I think I went the minmalistic route at first, but then decided to use the three letter naming, to format neatly. – vol7ron Sep 14 '11 at 04:09
  • Isn't `int` a reserved word in JS? Even SO is formatting it as a keyword. – Travis Watson Oct 23 '12 at 20:15
  • No, `int` is not a keyword in JS. It may be in C, but not JS. The code highlighter gets stuck on various things, not just this. – vol7ron Oct 23 '12 at 20:24
  • Ugh, I need to keep up with the times. `int` was a future reserved word in ECMAScript 3 but was removed in 5. Tested it in IE 6-8 and Chrome... looks like it's okay to use. ^_^ Carry on. – Travis Watson Oct 24 '12 at 02:09