Convert int to string with specific char length

If the name was not clear, try to explain it poorly here. I have a bunch of integers from 1 to 999 and I need to convert them to strings, but when I do this, I need them to be 3 characters long. so, for example, if I had:

int i1 = 45; 

then when I turned this into a string, I will need the following: "045" or similarly, if I had int 8, then it would have to turn into "008" , and if something had 3 places, like 143 then it will simply be output as 143. Is it easily possible?

Thanks for the answers in advance. :)

+4
source share
1 answer
 string output = someInt.ToString("000"); 

If you want to make it more dynamic, you would do something like this

 // where 'length' is 3 string output = someInt.ToString(new string('0', length)); // or string output = i.ToString().PadLeft(length, '0'); 
+17
source

Source: https://habr.com/ru/post/1312663/


All Articles