vijay

welcome Netizen

Share Your Knowledge.It is a way to achieve immortality

Monday, October 29, 2012

How to format string with leading zeros in C#


Here I share bit of useful code as we need to use normal project.
Consider a case we have string with single digit,we need to format string with adding leading zeros.
In that case you can use the below code to format string with leading zeros.
You can add leading zeros by using two different type of method code:

First Method:
   string srt = "45";
        //here i have string as two digit.now its going to format by adding zeros with 3 didgit
        Response .Write (srt.PadLeft  (3,'0'));

Output:
045

Second Method:
Same output we can get by using different code …
Response.Write (String.Format("{0:D3}",45));

Output:
045
Take another example to add leading zeros, consider we need to display  Time format.
We use Date time to get the current time.
Response.Write(String.Format("{0:D2}:{1:D2}:{2:D2}", DateTime.Now.Hour, DateTime.Now.Minute,DateTime.Now.Second));

Output:
09:07:44
I hope you like this article,Post your comments here..

Share this article with your friends using share button


0 comments:

Post a Comment