javascript中的千位分隔符

时间:2014-04-25 00:00:43

标签: javascript

我尝试做的是当我的html运行时,5888看起来像5,888,任何帮助都会受到赞赏。所以在你用html运行之后我想要" xxxx小时的倒计时单位圣诞"。问题是我想要" xxxx"作为" x,xxx"。

    <html>
<body>

<p>Clock!</p>
<div id = "string"></div>
<div id = "string2"></div>

<script>
var myVar=setInterval(function(){myTimer()},1000);

function myTimer()
{
var d=new Date();
var n=d.toLocaleDateString(); 
var t=d.toLocaleTimeString();
var m = d.toTimeString(); 
document.getElementById("string").innerHTML= n + m;

var b = new Date();
b.setFullYear(2014,11,25); 
var dateHour1 = b.getTime();
var minutes=1000*60;
var hours=minutes*60;
var xHour = Math.round((dateHour1 - d)/hours);
document.getElementById("string2").innerHTML = xHour +" Hours until xmas";
}
</script>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

您可以尝试以下功能:

// Format a number n using: 
//   p decimal places (two by default)
//   ts as the thousands separator (comma by default) and
//   dp as the  decimal point (period by default).
//
//   If p < 0 or p > 20 results are implementation dependent.
function formatNumber(n, p, ts, dp) {
  var t = [];
  // Get arguments, set defaults
  if (typeof p  == 'undefined') p  = 2;
  if (typeof ts == 'undefined') ts = ',';
  if (typeof dp == 'undefined') dp = '.';

  // Get number and decimal part of n
  n = Number(n).toFixed(p).split('.');

  // Add thousands separator and decimal point (if requied):
  for (var iLen = n[0].length, i = iLen? iLen % 3 || 3 : 0, j = 0; i <= iLen; i+=3) {
    t.push(n[0].substring(j, i));
    j = i;
  }
  // Insert separators and return result
  return t.join(ts) + (n[1]? dp + n[1] : '');
}

formatNumber(5888, 0) // 5,888