Add Leading Zeroes to SAS Data

By | October 6, 2009

saslogo You probably have many SAS data sets that you regularly work with where numbers are stored as text for formatting purposes.  A great example is the social security number, and many other customer, product, or invoice numbers are formatted similarly.  They frequently utilize leading zeros in their storage and display.  You probably also frequently receive data from colleagues where the same variable is formatted as a numeric value missing the leading zeros.  The join that you were going to do with your data and the data received from the colleague just won’t work.  Here is a little SAS code that can turn your colleague’s data into a match for yours, and I’ll use social security number (SSN) in this example:

data DatasetName ;
set InputDataset ;
length ssn_char $9. /* New Character var for SSN                    */
ssn_char = put(ssn,z9.) ; /* Put the Numeric SSN with the Z9. format   */
drop ssn ; /* Housecleaning to drop the numeric SSN    */
rename ssn_char = ssn ; /* Renamed Char SSN to make our Join easier */
run ;

By creating a new Character variable of SSN, I can simply put the Numeric SSN with Z9. format into the variable.

The format Z9. states the variable should be 9-bytes, and for each byte less than 9, put a leading zero in front of the var.

No strip or trim is necessary either.

I used this in the past with a transaction number I was creating (numeric) and later wanted to display it in a title with leading zeros [Example:  had 123 as the value, put it with a Z10. and the display in the title was 0000000123].

Thanks to Paula for showing me this trick!

4 thoughts on “Add Leading Zeroes to SAS Data

  1. Norman

    Thanks, this is exactly what I needed to “pad” an identifier with leading zeroes if only one or two digits were returned.

    This make the report look that little bit neater.

    Norman.

    Reply
  2. Fred Janssen Post author

    SAS formats really do a lot of cool things to make your life easier and present your output the way you want it. It is actually really simple too!

    Reply
  3. Norman

    OK, now I’ve come across something unexpected (for me, anyway). It seems that using the z2. format on missing data results in ** being displayed. Interesting, but I think the client would rather see nothing (blank space).

    Is there an easy way to “fix” this?

    Norman.

    Reply
    1. Fred Janssen Post author

      Without the code available, it’s hard to say what is causing your issue, but generally asterisks in output are an indication of a format width problem.

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *