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

3
  • How are you trying to apply the solution from the other question? It should work perfectly, just pass the number you want to format. Commented Jun 17, 2011 at 21:37
  • Works pretty well for me: jsfiddle.net/fkling/wnWVA What is your problem? Commented Jun 17, 2011 at 22:22
  • Check this npm package: reformat-number Commented Mar 10, 2018 at 1:26

4 Answers 4

18
(1234567890).toLocaleString();
Sign up to request clarification or add additional context in comments.

2 Comments

According to MDN, calling .toLocaleString without any arguments is supported across all browsers.
Thank you for this answer, was looking for something native and simple
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);

2 Comments

How do I integrate this with the function I'm using?
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.
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();

Comments

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

4 Comments

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.
Isn't int a reserved word in JS? Even SO is formatting it as a keyword.
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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.