Home  /  Resources & support  /  FAQs  /  Putting leading zeros in output

Is there a way to put leading zeros in output?

Title   Putting leading zeros in output
Author Gary Petersen, RRC Inc.

You can format variables to be reported with leading zeros by placing a zero after the percent sign using the %f format; see [D] format. For instance,

   . format ssn %09.0f

will pad the left side of the nine-digit number with zeros.

The leading zeros are seen on-screen when you list the variable and when you outfile the data.

Many Stata users also wish to convert numeric data to strings and keep the leading zeros, which is good for U.S. Social Security numbers, times, dates, etc. This conversion can be done using the string() function with an option for the format.

Below we show an example; the variable 'x' is a numeric value, and not a string.

    . list

         +-----+
         |   x |
         |-----|
      1. |  55 |
      2. |  23 |
      3. |  81 |
      4. | 144 |
      5. | 174 |
         |-----|
      6. |  92 |
      7. |  84 |
      8. | 178 |
      9. |  11 |
     10. | 135 |
         +-----+

    . gen str3 y = string(x)
    
    . list

         +-----------+
         |   x     y |
         |-----------|
      1. |  55    55 |
      2. |  23    23 |
      3. |  81    81 |
      4. | 144   144 |
      5. | 174   174 |
         |-----------|
      6. |  92    92 |
      7. |  84    84 |
      8. | 178   178 |
      9. |  11    11 |
     10. | 135   135 |
         +-----------+
        
    . gen str3 z = string(x,"%03.0f")
        
    . list

         +-----------------+
         |   x     y     z |
         |-----------------|
      1. |  55    55   055 |
      2. |  23    23   023 |
      3. |  81    81   081 |
      4. | 144   144   144 |
      5. | 174   174   174 |
         |-----------------|
      6. |  92    92   092 |
      7. |  84    84   084 |
      8. | 178   178   178 |
      9. |  11    11   011 |
     10. | 135   135   135 |
         +-----------------+

As you can see, the variable y was created and did not have a leading zero. By adding the format option to the string() function, we were able to manipulate the format of the data that were converted.