Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Adding zeros to a string variable

    Hi,

    Please let me know how can I add zeros to a string variable. for example, in my dataset, there is a variable called nic_code, and it ranges from 01000 to 99999. However, in the raw data, 01000, 02000,... have been written as 01, 02,.. only and it is a string variable. Could you please tell me how can I convert this into a string variable with 5-digits? for other numbers like 99988, the data looks ok.

    thank you so much

  • #2
    Code:
    clear
    input str5 broken 
    "99888"
    "01" 
    "02"
    end 
    
    gen fixed = broken + substr("00000", 1, 5 - length(broken))
    
    list 
    
          +----------------+
         | broken   fixed |
         |----------------|
      1. |  99888   99888 |
      2. |     01   01000 |
      3. |     02   02000 |
         +----------------+
    Extra detail: it does no harm to push your strings through trim() just to remove any leading or trailing spaces.

    Comment


    • #3

      Thank you so much for your reply. Thanks a lot.

      Comment

      Working...
      X