Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert int into string with certain length of char

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. :)

like image 619
caesay Avatar asked Jun 12 '10 22:06

caesay


1 Answers

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');
like image 147
Anthony Pegram Avatar answered Oct 16 '22 13:10

Anthony Pegram