convert int into string with certain length of cha

2020-04-07 04:46发布

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

1条回答
对你真心纯属浪费
2楼-- · 2020-04-07 05:42
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');
查看更多
登录 后发表回答