convert int into string with certain length of char

caesay picture caesay · Jun 13, 2010 · Viewed 9.9k times · Source

If the title wasn't clear, ill try to explain it well here. I have a bunch of integers, ranging from 1 to 999, and i need to convert these into strings, but when i do that, i need them to be 3 characters long. so for instance, if i had:

int i1 = 45;

then when i turned that into a string, i'd need this: "045" or similarly, if i had an int of 8 then that would have to turn into "008", and if anything had 3 places, such as 143, then it would just be outputted as 143. is this easily possible?

Thanks for responses in advance. :)

Answer

Anthony Pegram picture Anthony Pegram · Jun 13, 2010
string output = someInt.ToString("000");

If you would like 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');