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

喜夏-厌秋 提交于 2019-12-14 00:52:46

问题


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?


回答1:


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.




回答2:


string test = "9163";
test = test.PadLeft (5, '0');



回答3:


  string s = string.Format("{0:00000}", 1234);

  Console.WriteLine(s);

Format String Reference




回答4:


string one = a.ToString("00000"); // 00904


来源:https://stackoverflow.com/questions/16838782/simple-and-elegant-way-to-zero-pad-a-value-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!