BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.

I have a dataset with values like this (it is a character with length of 7)

 

AFF.PNG

 

What I want is this - IF the actual value is less than 5 digits, add zeros to the beginning of the value until it is 5 digits long. 

1 ACCEPTED SOLUTION

Accepted Solutions
Astounding
PROC Star

A simple loop could do it:

 

do while (length(var) < 5);

   var = '0' || var;

end;

View solution in original post

6 REPLIES 6
novinosrin
Tourmaline | Level 20
data want;
set have;
if length(var)<5 then var=reverse(substr(strip( reverse(var))||'00000000',1,5) ); 
run;
 
Regards,
Naveen Srinivasan
Astounding
PROC Star

A simple loop could do it:

 

do while (length(var) < 5);

   var = '0' || var;

end;

bollurajkumar
Fluorite | Level 6

hi

the

 

variable is numeric so use formate option

 

DATA test_data1; 
input studyid ; 
format studyid z8.; 
cards;
543
243
15967
26484143651
5442
124
1
23
4423
;
run;

formate zw.

 

w means total how many digits you want with zeros

JediApprentice
Pyrite | Level 9

@Astounding How exactly does this work? How is the data step looping back to keep adding zeros - I get that there's the while condition, but say I have 123 which needs  2 zeros in front of it. Data step will go through the loop to put the first 0 in front. How does it come back to that observation to add another zero? I know it has to do with the condition and the PDV, just not sure of the details...

Astounding
PROC Star

It's the logic of DO WHILE.

 

After the first time through the loop a single zero has been added:  0123

 

The DO WHILE condition is still true, since the length is now 4.  So the loop executes a second time, adding another zero:  00123

 

Now the DO WHILE condition is false, so the loop ends.

thomp7050
Pyrite | Level 9
DATA test_data1; 
length studyid $50;
input studyid $;  
cards;
543
243
15967
26484143651
5442
124
1
23
4423
;
run;

data test_data1;
set test_data1;
if length(studyid) < 5 THEN DO;
studyid = repeat('0',5-length(studyid)) || studyid;
END;
run;

sas-innovate-2024.png

Join us for SAS Innovate April 16-19 at the Aria in Las Vegas. Bring the team and save big with our group pricing for a limited time only.

Pre-conference courses and tutorials are filling up fast and are always a sellout. Register today to reserve your seat.

 

Register now!

How to Concatenate Values

Learn how use the CAT functions in SAS to join values from multiple variables into a single value.

Find more tutorials on the SAS Users YouTube channel.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

Discussion stats
  • 6 replies
  • 1074 views
  • 5 likes
  • 5 in conversation