3

这是我的程序:

<script>
var montharray = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")

function countup(yr, m, d) {
    var today = new Date()
    var todayy = today.getYear()
    if (todayy < 1000) todayy += 1900
    var todaym = today.getMonth()
    var todayd = today.getDate()
    var todaystring = montharray[todaym] + " " + todayd + ", " + todayy
    var paststring = montharray[m - 1] + " " + d + ", " + yr
    var difference = (Math.round((Date.parse(todaystring) - Date.parse(paststring)) / (24 * 60 * 60 * 1000)) * 1)
    difference += ""
    document.write("" + difference + "")
}
//enter the count up date using the format year/month/day
countup(2007, 01, 24)
</script>

我试图让输出在数千个位置插入逗号(例如 1,234 而不是 1234)。我怎样才能做到这一点?

4

1 回答 1

3

To add commas to every third, simply iterate over the number converted to string from the back and every third, add a comma.

var str = "" + num;
var s2 = "";
for( var i = str.length()-1; i != 0; i-- ){
    s2 += str.charAt(i);
    if( 0 == (str.length() - i) % 3 )
        s2 += ",";
}

Or such. Not sure about the math.

于 2011-08-07T03:59:23.377 回答