Click to See Complete Forum and Search --> : counter with multiple digits


bol
07-15-2006, 12:51 AM
Hi all.

I would like to make a counter which simply outputs a number, which I can use in a string. it should be zero based and start at 000001 for the first batch of numbers and 111001 for the second batch of numbers

The only requirement is that the output of the counter maintain six digits as they are to be used to reference file names all of which are six digits long.

so the numbers should go ...000009, 000010, 000011... etc

so far I can only make it go ...000009, 0000010

It's annoying. is there a quick way of doing this?

-edit - the only way I can get it working is to add the ones or zeros on as a string in front of the actual number... but this can't be the correct way to do it.

BigMoosie
07-15-2006, 01:47 AM
If you want leading zeros then you will have to deal with strings.
Number.prototype.format = function(){
var s=this+'';
while (s.length<6) s='0'+s;
return s;
};

//example usage:
document.write((43).format());

bol
07-15-2006, 04:34 AM
Many thanks.. :D

JMRKER
07-15-2006, 10:35 AM
You could alternatively use:


<htm>
<head>
<title>Left Pad Test</title>

<script type="text/javascript">
<!--
LpadStr = function(Str,NP) {
while (Str.length < NP) { Str = '0'+Str; }
return Str;
}
//-->
</script>
</head>

<body>
Enter number: <input id="StrInt" type="text" value="">
Left pad value: <input id="LPad" value="6" size="2">
<br />
<button
onClick="document.getElementById('StrStr').value
= LpadStr(document.getElementById('StrInt').value,document.getElementById('LPad').value)">
Do it!</button>
Pad left value:
<input id="StrStr" type="text" value="">
</body>
</html>

The advantage here is that the leading pad value could be a variable.
Also, slight modification to pad value could LpadStr() with spaces rather than '0's