Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

zero-pad

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?

like image 731
Tim Avatar asked May 30 '13 14:05

Tim


1 Answers

string test = "9163";
test = test.PadLeft (5, '0');
like image 168
Andrew Avatar answered Oct 02 '22 14:10

Andrew