Discover More Tips and Techniques on This Blog

How to add leading zeros to numeric variables

Have you ever asked to create a variable with leading zeros? I mean 1 to 001 and 2 to 002. If you were, do you know how....

SAS has a special numeric format Zw.d. which can include leading zeros.

Zw.d Format in which,
w : Width of variable.

d : Decimal Point.
Zw.d format writes standard numeric data with leading 0's. The Zw.d format is similar to the w.d format except that Zw.d pads right-aligned output with 0s instead of blanks. (Ref: SAS 9.2 Language Reference : Dictionary, 4th edition);


Let me give you a scenario where this can be very useful:

You have a variable called site with the numbers as 101, 999, 1001 and 1200. If you want to create a USUBJID variable with fixed length for all the subjects, we need to modify the site variable variables to fixed length. (length=4). You can do that using Z4.d format.

Note: As this is a numeric format, this can be applied to numeric variables only.

*z4.format is used to add the leading zeros to site variable;


data have;
     length site $4;
site='101';  subject='1001';output;
site='129';  subject='1002';output;
site='999';  subject='1003';output;
site='1000'; subject='1004';output;
site='1010'; subject='1005';output;
site='1011'; subject='1006';output;
run;

data want;
length usubjid $19;
set have(rename=(site=sitec));
studyid='ABC10049';
site=put(sitec+0,z4.); *Z4. format is applied after converting the character variable sitec to site; 
usubjid=catx('-',studyid,site,subject);
        keep usubjid site;
run;



Output:


USUBJID                         SITE
ABC10049-0101-1001 0101
ABC10049-0129-1002 0129
ABC10049-0999-1003 0999
ABC10049-1000-1004 1000
ABC10049-1010-1005 1010
ABC10049-1011-1006 1011


You could also use REPEAT function also:

Here is how...

site=catt(repeat('0',3-length(sitec)),sitec);

Please note that the 3 reference to the minimum length of site variable. I have used 3 because the minimum length in the given example is 3.




Disclosure:

In the spirit of transparency and innovation, I want to share that some of the content on this blog is generated with the assistance of ChatGPT, an AI language model developed by OpenAI. While I use this tool to help brainstorm ideas and draft content, every post is carefully reviewed, edited, and personalized by me to ensure it aligns with my voice, values, and the needs of my readers. My goal is to provide you with accurate, valuable, and engaging content, and I believe that using AI as a creative aid helps achieve that. If you have any questions or feedback about this approach, feel free to reach out. Your trust and satisfaction are my top priorities.