Geeks With Blogs


Microsoft MVP


Moderator at CodeASP.NET

Quiz Master

free counters
Free counters
Added on January 19,2012

Follow Me @vmsdurano

A bit About Me

The opinions expressed herein are my own personal opinions and does not represent the opinions of my employers. Nor does it represent the opinion of my dog, because I don’t have one.

Vinz' Blog (ProudMonkey) "Code, Beer and Music ~ my way of being a programmer"

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");



        //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!


Technorati Tags: ,,
Posted on Wednesday, August 12, 2009 8:56 PM ASP.NET , C# , Tips&Tricks | Back to top

Comments on this post: Retain Leading Zeros when Converting from Int to String

comments powered by Disqus

Copyright © Vincent Maverick Durano | Powered by: