Wednesday, February 3, 2010

C#: Padding an Integer with Leading Zeroes

I find this method useful sometimes when displaying time of day, receipt codes or other numerical data. It takes an integer and a width and returns a zero-padded string representation of the integer. It's a simple method yeah but I've seem implementations on the web where people assemble a string using a while loop with a StringBuilder, and sometimes just using the + operator, disgusting.

Example: To get "00053" from the integer 53, call PadIntToStr(53, 5)

public static string PadIntToStr(int i, int maxWidth)
{
            bool ltz = i < 0;
            int diffLen = maxWidth - i.ToString().Length;
            string pole = string.Empty;

            if (diffLen <= 0)
                return i.ToString();

            if (ltz)
            {
                i = Math.Abs(i);
                pole = "-";
            }

            return string.Format("{0}{1}{2}", pole, new string('0', diffLen), i);

}

No comments:

Post a Comment