6

I have to fix malformed zipcodes. The people who exported the data treated the zipcode as a numeric and as a result New Jersey and Puerto Rico zipcodes, which begin with a leading zero and two leading zeroes respectively, have been truncated.

They're supposed to be all five characters (no zip+4 data is involved). I know how to zero-pad brute-force by getting the length and prepending the appropriate number of zeroes to the string, but is there a more elegant way that draws on the "native" features of C#? For example, can a mask be applied that would turn "9163" into "09163" and "904" into "00904" without my having to get the length of the value?

Tim
  • 8,669
  • 31
  • 105
  • 183
  • 2
    BTW: must be a duplicate several times over.... – Mitch Wheat May 30 '13 at 14:32
  • http://stackoverflow.com/questions/3122677/add-zero-padding-to-a-string, http://stackoverflow.com/questions/4325267/c-sharp-convert-int-to-string-with-padding-zeros, http://stackoverflow.com/questions/3459610/pad-with-leading-zeros, http://stackoverflow.com/questions/11901395/pad-left-with-zeroes, etc.. you'd really hope an admin would search first! ;) – Mitch Wheat May 30 '13 at 14:45

4 Answers4

10
string test = "9163";
test = test.PadLeft (5, '0');
Ilya Ivanov
  • 23,148
  • 4
  • 64
  • 90
Andrew
  • 2,315
  • 3
  • 27
  • 42
8

If you have an integer value, use the composite format string to ensure padding:

var padded1 = 1.ToString("D5");

The number after D is for the length you need the value to be in.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
  • Thank you, it works when the original string value was truncated and turned into a numeric, as in my scenario. – Tim May 30 '13 at 14:39
3
  string s = string.Format("{0:00000}", 1234);

  Console.WriteLine(s);

Format String Reference

Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541
2
string one = a.ToString("00000"); // 00904
h.meknassi
  • 189
  • 8