views:

51

answers:

5

hello.. i just want to ask if how to convert the number to String.. what i want to output is "000000" incremented per second "0000001".. i tried different methods but it will output to 1,2,3... i tried this but still won't work..

 $(document).ready(function(){
  xx();
  var x = 0;

  function xx()
  {

    x++;
    if(x.length==5) {
        x = "00000" + convert.toString(x);
    }

    $("div.sss").text(x);


    setTimeout(xx,1000);
  }

 });
A: 

Since x is Number is will not have a length property so x.length==5 will always evaluate as false so your attempt to prefix it with a series of zeros will never be executed.

If it was executed, then it would fail because convert is undefined.

David Dorward
+2  A: 

Like this:

function padString(str, size) {
    str = "" + str;
    if (str.length >= size)
        return str;
    return "00000000000000000000000000".substr(0, size - str.length) + str;
}
SLaks
A: 
function xx()
{
    x++;
    str_x = "000000"+x;
    str_x = str_x.substring(str_x.length - 6);
    $("div.sss").text(str_x);
    setTimeout(xx, 1000);
}
Ned Batchelder
A: 

you don't need to use toString. You can do "foo" + x or "00000" + x directly

動靜能量
A: 

This works:

$(document).ready(function() {

 var x = 0;

 function loop() {
  var t = x + "";
  var n = 6 - t.length;

  while (n > 0) {
   t = "0" + t;
   n -= 1;
  }
  $("#foo").text(t);    
  x += 1;   
  setTimeout(loop, 1000);
 }

 loop();

});
Šime Vidas