String formatting

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

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
 
Hi trickytrini,

You are looking for String.PadLeft

int n = 1;
string s = n.ToString().PadLeft(3, '0');
 
There are PadLeft and PadRight methods on the string class to do this. One
of the overloaded versions allows you to specify a character.
 
Thanks!

Marina said:
There are PadLeft and PadRight methods on the string class to do this. One
of the overloaded versions allows you to specify a character.

trickytrini said:
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
 
Back
Top