A simple and elegant way to zero pad value in C #

I need to fix invalid zipcodes. The people who exported the data treated the zipcode as numeric and, as a result, the New Jersey and Puerto Rico postal codes, which start with a leading zero and two leading zeros, respectively, were truncated.

They are supposed to be five characters (no data on zip + 4). I know how to use zero-load brute force by getting the length and adding the appropriate number of zeros to the string, but is there a more elegant way that relies on the "native" C # functions? For example, can a mask be applied that turns "9163" into "09163" and "904" into "00904" without my need to get the length of the value?

+4
source share
4 answers

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

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

The number after D corresponds to the length in which the value should be.

+6
source
 string test = "9163"; test = test.PadLeft (5, '0'); 
+8
source
 string one = a.ToString("00000"); // 00904 
+2
source
  string s = string.Format("{0:00000}", 1234); Console.WriteLine(s); 

String Formatting Reference

+2
source

Source: https://habr.com/ru/post/1483601/


All Articles