Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsFree MagazinesWhite PapersSubmit Content
Discussion GroupsASP.NETWindows FormsLanguages.NET FrameworkVisual Studio.NET
Articles.NET FrameworkASP.NETToolsWindows Forms
.NET DirectoryOpen Source ProjectsUser GroupsWeb Resources
Related Topics
Visual Basic 6SQL ServerMS AccessOther DB ProductsMS Server ProductsMore Topics ...

.NET Forum / .NET Framework / New Users / May 2005

Tip: Looking for answers? Try searching our database.

String formatting

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
trickytrini - 05 May 2005 17:12 GMT
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

Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.