Add Lead Zeros to Numbers in Stata

  EDS > Add Lead Zeros to Numbers in Stata
printer friendly version Print
Page

If you have numeric data that needs leading zeros, e.g. Census tract numbers, Social Security numbers, dates, etc., you can add lead zeros by turning the numbers into strings using the string() function with a format option.

Suppose your data has a three-digit ID variable that looks like this:
   1
   7
  11
  41
 103
To turn it into a string variable with lead zeros, give this command:
      gen str3 ID_Z = string(ID,"%03.0f")
The new variable ID_Z looks like this:
 001
 007
 011
 041
 103
Remember that this is a string variable. Also, note that, if you are matching to another file, the variables in both files must be strings of the same length.