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;
se开发者_开发百科tInterval("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
(1234567890).toLocaleString();
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);
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();
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;
}
精彩评论