Reputation: 15
I'm trying to loop through a range of numbers in NodeJS, but not by using integers, by using a string.
For example, I want to loop through from 000000 to 500000. Ie. 000001, 000002, all the way to 500000. When percieved as an integer, NodeJS will just go 1, 2, all the way up to 500000. I want to keep if so the number always has 6 digits and loops through every possible number.
Edit: I need it to loop through like 000001, 000002, ..., 000010, ... , 000100, ... , 001000, ... , 010000, ... , 100000, ... , 500000. Filling in every number in between though
Thanks in advance
Upvotes: 0
Views: 725
Reputation: 92440
If you're using a relatively new version of node you can use string.padStart()
:
for(var i = 0; i <= 500000; i++) {
str = i.toString().padStart(6, 0)
// 000001, etc
}
More docs here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
Upvotes: 3
Reputation: 1937
Iterating through the number as usual but padding 0's before it.
function pad (str, max) {
str = str.toString();
return str.length < max ? pad("0" + str, max) : str;
}
for(var i = 0; i <= 500000; i++) {
console.log(pad("6", i)) ;
}
Upvotes: 0