0

Setup: I have a number that is 10 positions. The number counts up from 0000000000 so that the first number would be 0000000001 followed by 0000000002 and so on. So i know the total number of positions in the string. I want to figure out how to get the total number of zeros i need to append to the beginning of the string. For example, i can look at the ID of an item and see it is "123" and i know that the "name" of the item is "0000000123". So im trying to figure out the best way to get the total number of zeros that need to be added to the beginning of the String to make it 10 characters long in total.

I know that i could use if, else if and go through every single position but i know there has to be a "better" more efficient way. My coding knowledge is sub par so off the top of my head i am not sure where to start. Any help in the right direction would be appreciated. I am also googling for ways but wanted to get this posted here in case anyone wants to give me some pointers.

user3205214
  • 65
  • 1
  • 7
  • 3
    123 is 3 characters long, so you need to pad it with 7 zeros to make 10 characters long. Am I missing something? – Andy Turner Jul 19 '18 at 22:05
  • Any reason not to manipulate it as a number (instead of a string) and output with leading zero formatting? – wallyk Jul 19 '18 at 22:06
  • [This question](https://stackoverflow.com/questions/1306727/way-to-get-number-of-digits-in-an-int) has some good answers about how to get the number of digits an `int` has. If `ID` is a `String` then what _Andy Turner_ mentions is probably best: simply add `10 - string.length()` 0's. – Slaw Jul 20 '18 at 00:08
  • i was using 123 as an example. the id could be "1" or "1234" or even "1234567" and depending on that i would need to append the correct number of zeros to the beginning to get a 10 character number with leading zeros. Again, i know i can use an if statement followed by else if statements to go through all 10 characters but i know there has to be a better way to go about doing it. – user3205214 Jul 20 '18 at 14:26
  • thanks @AndyTurner for linking the previously asked questions – user3205214 Jul 20 '18 at 14:31

0 Answers0