Vinz' Blog

"Code, Beer and Music" ~ my way of being a programmer!
posts - 124, comments - 367, trackbacks - 0

My Links

News

Archives

Image Galleries

Retain Leading Zeros when Converting from Int to String

Many members in the forums are asking if why is it that an integer value with a leading zero is being trimmed off when converting it to a string?

 

Consider this example:

 

        int num = 0123456; // a 7 numbers

        string sNum = num.ToString();

 

        //The result will give you 123456

 

 

What happened to the leading zero?

 

Well basically, leading zero has no significance to an integer because by nature an integer with a value of 01 is simply the same as 1. So based on the example above we have an integer value of 0123456 and basically it outputs 123456 (without the leading zero).

 

How can we retain them when we need to display them?

 

That’s the main reason why I decided to write this post. Here’s one way on how to retain them when converting it to string.

 

        int num = 0123456; // a 7 numbers

        string sNum = num.ToString("0000000");

 

        Response.Write(sNum);

        //The result will give you 0123456

 

The trick there is we used ToString() with the format "0000000" where the number of zero is equal to number of digits your integer has. So since we have a 7 digit integer value then we used 7 zeros in the format.

 

That’s it! Hope you will find this post useful!

Print | posted on Wednesday, August 12, 2009 8:56 PM |

Feedback

No comments posted yet.
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 
 

Powered by: