2013-12-09 54 views
1

我有一个脚本,用于计算每秒钟有多少(小狗和小猫)。它使用Date()来计算一个月的开始和一个月初的开始时间。但是我很难更新这个脚本来添加数千,数百万亿分号的逗号。有人可以告诉我在这个脚本中添加逗号的最佳方式吗?如何将逗号更改为使用setInterval()更新的值

这里去了jsFiddle

var start = new Date(), 
    midnight = new Date(start.getFullYear(), start.getMonth(), start.getDate(), 0), 
    first = new Date(start.getFullYear(), start.getMonth(), 1); 

var now = new Date(), 
    secondsFromStart = Math.floor((now - start)/1000), 
    secondsFromMidnight = Math.floor((now - midnight)/1000), 
    secondsFromFirst = Math.floor((now - first)/1000); 

var elems = []; 
$(".s").each(function(){ 
    var $this = $(this); 
    var BornPerSec = $this.data("quantity"), 
     Start = secondsFromStart*BornPerSec, 
     Midnight = secondsFromMidnight*BornPerSec, 
     First = secondsFromFirst*BornPerSec; 
    elems.push({ 
     obj: $this, 
     BornPerSec: BornPerSec, 
     Start : Start, 
     Midnight : Midnight, 
     First : First,  
     now: $this.children('.now'), 
     morning: $this.children('.morning'), 
     month: $this.children('.month'), 
    }); 
}); 
setInterval(function() { 
    $.each(elems,function(i,n){ 
     n.Start+=n.BornPerSec; 
     n.Midnight+=n.BornPerSec; 
     n.First+=n.BornPerSec; 
     n.now.text(n.Start % 1 === 0 ?n.Start: n.Start.toFixed(2)); 
     n.morning.text(n.Midnight % 1 === 0 ?n.Midnight:n.Midnight.toFixed(2)); 
     n.month.text(n.First % 1 === 0 ?n.First:n.First.toFixed(2)); 
    }); 
}, 1000); 
+0

可能重复[如何打印带有逗号作为在JavaScript千位分隔符的数] (http://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript) – charlietfl

+0

@charl ietfl - 谢谢,但这个问题并不是真正的骗局,因为值总是在更新中 –

+0

这就是你如何得到重要的分隔符,这就是你要求的 – charlietfl

回答

1

您可以尝试使用此功能:

function numberWithCommas(x) { 
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); 
} 

Updated jsFiddle demo

+0

谢谢!精美地工作! –

相关问题