Reputation: 1
I'm fairly new to Javascript and have been able to get by so far by just following tutorials and reading forums but this one really stumped me for a while.
Basically I wanted to have a counter for numbers that contain seven digits, I found a few things but none that really made sense to me so I wrote this:
imgNumber++;
if (imgNumber < 10){function add(number){return '00000' + number}};
if (imgNumber > 10 && imgNumber < 100){function add(number){return '0000' + number}};
if (imgNumber > 100 && imgNumber < 1000){function add(number){return '000' + number}};
if (imgNumber > 1000 && imgNumber < 10000){function add(number){return '00' + number}};
if (imgNumber > 10000 && imgNumber < 100000){function add(number){return '0' + number}};
if (imgNumber > 100000 && imgNumber < 1000000){function add(number){return '' + number}};
It works as far as I can tell. My question is this: Do you foresee any issues with this and if not is there a cleaner way to write all this?
I'll appreciate any and all replys.
Cheers, Colin
Upvotes: 0
Views: 1017
Reputation: 955
As with all programming functions are your friend. I searched google for padding zeros javascript and got directed to this site.
function pad(number, length) {
var negative = number < 0;
var str = '' + Math.abs(number);
while (str.length < length) {
str = '0' + str;
}
if(negative) str = '-' + str;
return str;
}
Using this you would just generate your number standard and prior to storing/outputting it you'd run it through this function:
pad(1,7);
Upvotes: 2
Reputation: 3391
A one liner:
var output = sprintf("%07d", 30);
Believe me, it will save you a lot of time in javascript (and in other languages). You can download the implementation in http://sprintf.googlecode.com/files/sprintf-0.7-beta1.js
By today, this code works right now, perhaps you need to change the src of the library for a more updated:
<script type="text/javascript" src="http://sprintf.googlecode.com/files/sprintf-0.7-beta1.js"> </script>
<script type="text/javascript" >
alert(sprintf("%04d",4));
</script>
More information, here, plus there are other implementations of this useful method.
Upvotes: 1
Reputation: 2282
Why don't you just take the log (base 10) of the number as an indicator of how many digits to add.
If log(N) is between 0 and less than 1, N is a one digit number.
If log(N) is greater than or equal to 1 but less than 2, N has two digits, and so forth.
I don't actually code in JavaScript, so I don't know if you have access to a log function, but if you do, this is a very terse way to get the result.
John Doner
Upvotes: 0