Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Padding a value with ZEROS until a certain amount of characters 1

Status
Not open for further replies.

RascaPR

Technical User
Oct 27, 2007
26
US
Hello all,

I know that in PHP, if you want a variable to always be say 3 characters in length and the value is 1 or 2 characters, you can use the sprintf command to insert as many characters of your choice, until the variable reaches the specified length.

How can I do the same with Visual C#? BTW, I need to add the zeros to the left of the character.

Thanks for any help.
 
how about

int totalChars;
int numCharsToAdd = 0;
string yourString;

numCharsToAdd = totalChars - yourString.Length;

for (int x=0; x<numCharsToAdd;x++)
yourString = "0" + yourString;


probably an easier way to do this but this will work.

 
Hello bouwob,

The problem with this is that it has a fixed value for the amount of variables to add. This doesn't work for me. For instance, if I want the variable to have 3 characters all the time, then the program will add as many zeros to the variable until it is 3 characters in length.
 
could you please elaborate on that last statement. Im not following what you mean.
 
If v=4 then I want v=004
If v=44 then I want v=044
If v=444 then I want v=444
 
string.PadLeft(3,'0');

Does that do what you want? The first parameter is the required length, second parameter is the char to fill with. There's also a PadRight.
 
the string.PadLeft command worked perfectly! THANKS!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top