Is there a way to format a string so that it is always left padded with zero's?
For example I have random set of number say: 1, 40, and 389. I want to
always display the number 3 digits padded with zeros like:
001, 040, and 389.
I have the following code, and I am not sure if there is a way like C to do
this in .net:
int digit1 = 3, digit2=40;
string display;
display = string.Format( "[{0,2:3}] and [{1,2:3}]", digit1, digit2 );
the output for this is:
"[ 3] and [ 40]"
Its padded with spaces instead of zeros.
I know I'm just missing something in the doc. Anyone have any ideas?
~ trickytrini
Morten Wennevik - 05 May 2005 18:54 GMT
Hi trickytrini,
You are looking for String.PadLeft
int n = 1;
string s = n.ToString().PadLeft(3, '0');

Signature
Happy coding!
Morten Wennevik [C# MVP]
trickytrini - 05 May 2005 21:30 GMT
Thanks!
> Hi trickytrini,
>
> You are looking for String.PadLeft
>
> int n = 1;
> string s = n.ToString().PadLeft(3, '0');
Marina - 05 May 2005 18:56 GMT
There are PadLeft and PadRight methods on the string class to do this. One
of the overloaded versions allows you to specify a character.
> Is there a way to format a string so that it is always left padded with
> zero's?
[quoted text clipped - 22 lines]
>
> ~ trickytrini
trickytrini - 05 May 2005 21:29 GMT
Thanks!
> There are PadLeft and PadRight methods on the string class to do this. One
> of the overloaded versions allows you to specify a character.
[quoted text clipped - 25 lines]
> >
> > ~ trickytrini