padding a numbers string reprensentation

  • Thread starter Thread starter Matthias S.
  • Start date Start date
M

Matthias S.

Hi,

I'm pretty sure this is as easy as it gets, but I couldn't find anything
in the documentation.

I'd like to change the string representation of an int so that the
numbers get padded with 0's up to a certain amount of characters: For
example I'd like to pad up to 4 characters, then a 17 should look like
this '0017'.

Any help is greatly appreceated.

Matthias
 
I don't recall the specifics, but if you look up standard formatting codes
under String.Format() in the docs you'll find a way to do it with
someInt.ToString(someFormatStringHere).

Another way would be:

int intDesiredLength = 10;
string s = someInt.ToString();
return new String('0',intDesiredLength - intDesiredLength) + s;

--Bob
 
It's even easier than that:

string s = iWork.ToString().PadLeft(10, '0');

gives a sting representation of an integer 10 digits long
padded left with 0's where iWork is just some integer you
are working with.

Les
 
I think the easier implementation would be:

int i = 17;
string s = i.ToString().PadLeft(4, '0')
 
Back
Top