Simple and elegant way to zero-pad a value in C# [duplicate]
Asked Answered
G

4

7

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?

Glycerinate answered 30/5, 2013 at 14:25 Comment(2)
BTW: must be a duplicate several times over....Karikaria
#3123177, #4325767, https://mcmap.net/q/216429/-pad-with-leading-zeros-duplicate, https://mcmap.net/q/378454/-how-to-pad-left-a-number-with-a-specific-amount-of-zeroes, etc.. you'd really hope an admin would search first! ;)Karikaria
E
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.

Expunge answered 30/5, 2013 at 14:27 Comment(1)
Thank you, it works when the original string value was truncated and turned into a numeric, as in my scenario.Glycerinate
P
10
string test = "9163";
test = test.PadLeft (5, '0');
Percutaneous answered 30/5, 2013 at 14:28 Comment(2)
string paddedString = test.PadLeft (5, '0');Archimandrite
Thank you, it works when the truncated value is a string.Glycerinate
E
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.

Expunge answered 30/5, 2013 at 14:27 Comment(1)
Thank you, it works when the original string value was truncated and turned into a numeric, as in my scenario.Glycerinate
K
3
  string s = string.Format("{0:00000}", 1234);

  Console.WriteLine(s);

Format String Reference

Karikaria answered 30/5, 2013 at 14:29 Comment(1)
Thank you for the string-mask approach.Glycerinate
L
2
string one = a.ToString("00000"); // 00904
Lukash answered 30/5, 2013 at 14:28 Comment(1)
Thank you, easiest for me to remember.Glycerinate

© 2022 - 2024 — McMap. All rights reserved.