Force length on integer in C#

May 1, 2006

Today, I had to do file renaming on 1.000 files in a directory so they could be sorted alphabetically. I will not go into details, but it was a lot trickier than anticipated because the original filenames where very different.

Basically, I wanted all filenames to be 4 digits long, so that 1.psd became 0001.psd and 754.psd became 0754.psd

In order to do that, I needed a method that would prefix any given number with the right number of zeros. So I came up with this:

private static string ForceLength(int number, int length)
{
   string s = number.ToString();
   string returnString = "";

   for (int i = s.Length; i < length; i++)
   {
      returnString += "0";
   }

   return returnString + s;
}

If you pass 54 as the number parameter and 4 as the length parameter, the method returns "0054".

I’m not sure this is the best way to go, but it works. What do you think?

* Only $4.95/month ASP.NET & Windows 2008 + IIS 7 Hosting! FREE SQL Included

Comments (4) -

 Morten Rugaard
Morten Rugaard
5/3/2006 7:24:24 AM #

Im not a C# coder, but I would do about the same thing i PHP Smile
So I'm sure, that you did the right thing ;)

 kimblim
kimblim
5/3/2006 7:54:04 AM #

In PHP I would also go through the loop, but instead of adding the "0" manually, I would use %04d..

I am not sure there is a function like that in C#, but I wouldn't be surprised..

Jan Schreuder
Jan Schreuder
5/4/2006 5:13:17 PM #

You can do it so much easier: number.ToString().PadLeft(4, '0')

Here's the MSDN documentation: msdn2.microsoft.com/en-us/library/92h5dc07.aspx

I use it alot myself to right-align strings.

 Mads Kristensen
Mads Kristensen
5/4/2006 6:43:39 PM #

Thanks Jan

That was actually what I was looking for until I gave up and went with the method above. I have never used the PadLeft or PadRight before, and have always wondered what they did, but never took a minute to investigate. I've never needed it anyway, but it's always nice to learn something new. Thanks.

Comments are closed

About the author

Mads Kristensen

Mads Kristensen
Program Manager at the Microsoft Web Platform team and founder of BlogEngine.NET.

More...

Month List

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.