i have a number limit i.e. 000 now i want to increment it by 1 so the next limit will be '001' but when i try to add it gives me '1', also if somehow i figure out to maintain it '001', the second problem is after '009' there should be '010'. Advance Thanks for you efforts.
Asked
Active
Viewed 42 times
-3
-
1So, just have a number variable that you're incrementing, then _left pad_ it to 3 characters... – Cerbrus Oct 08 '18 at 07:03
-
1Try: `('000' + ++count).slice(-3)` – Rajesh Oct 08 '18 at 07:03
-
1Possible Duplicate: https://stackoverflow.com/questions/1267283/how-can-i-pad-a-value-with-leading-zeros – Rajesh Oct 08 '18 at 07:05
-
1Possible duplicate of [How can I pad a value with leading zeros?](https://stackoverflow.com/questions/1267283/how-can-i-pad-a-value-with-leading-zeros) – VLAZ Oct 08 '18 at 07:12
1 Answers
1
Thats padding.
function pad(num, size) {
var s = "000" + num;
return s.substr(s.length-size);
}
Assuming you'll never need more than 3 digits
[Edit] - For those who like early technology i.e ES7
There is a new method called padStart()
padStart - The padStart() method pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length. The padding is applied from the start (left) of the current string.
Example 1
const digits = 3
digits.toString().padStart(3, '0') // prints 003
Example 2
const digits = 76
digits.toString().padStart(3, '0') // prints 076

Nelson Owalo
- 2,324
- 18
- 37