Hi,
I want to Add zero(0) in prefix wherever the length(Have) less then “3” and blank as blank.
Have | Length | Want | Length |
112 | 3 | 112 | 3 |
12 | 2 | 012 | 3 |
12345 | 5 | 12345 | 5 |
cg.56 | 5 | cg.56 | 5 |
87 | 2 | 087 | 3 |
1 | 1 | 001 | 3 |
112 | 3 | 112 | 3 |
1frt. | 5 | 1frt. | 5 |
e | 1 | 00e | 3 |
0 | 1 | 000 | 3 |
kindly help.
Thanks,
Siva
both have and want variables should be a char type: (code fixed)
length want $10; /* adapt length to max length of have */
len = length(strip(have));
if len < 3 then want = substr('00',1,3-len) || left(have);
else have = want;
both have and want variables should be a char type: (code fixed)
length want $10; /* adapt length to max length of have */
len = length(strip(have));
if len < 3 then want = substr('00',1,3-len) || left(have);
else have = want;
Here's one approach, within a DATA step:
select (lengthn(have));
when (1) want = '00' || have;
when (2) want = '0' || have;
otherwise want=have;
end;
@sivastat08 wrote:
Hi,
I want to Add zero(0) in prefix wherever the length(Have) less then “3” and blank as blank.
Have Length Want Length 112 3 112 3 12 2 012 3 12345 5 12345 5 cg.56 5 cg.56 5 87 2 087 3 1 1 001 3 112 3 112 3 1frt. 5 1frt. 5 e 1 00e 3 0 1 000 3
kindly help.
Thanks,
Siva
How about SUBSTR on the left side of assignment statement equal sign.
data l0;
infile cards missover;
input Have $ Length1 xWant $ Length2;
l = lengthn(have);
if 0 eq l or l ge 3 then want = have;
else do;
want = '000';
substr(want,3-l+1)=have;
end;
z = compare(xwant,want);
cards;
112 3 112 3
12 2 012 3
12345 5 12345 5
cg.56 5 cg.56 5
87 2 087 3
1 1 001 3
112 3 112 3
1frt. 5 1frt. 5
e 1 00e 3
0 1 000 3
;;;;
run;
proc print;
run;
Simple substr() function will do it:
data want; input have $; want=substr(cats("00",have),lengthn(cats("00",have))-2); datalines; 112 12 1 ; run;
@RW9 If you want your solution to support strings longer than 3 characters then add a MIN() function.
data want;
length have want $10;
input have $;
want=substr(cats('00',have),min(3,length(cats('00',have))-2));
put have= want= ;
datalines;
112x
12
1
;;;;
I would change your choice of solution to any one of the other solutions offered, since @Shmuel's proposed solution simply won't work.
Art, CEO, AnalystFinder.com
@art297, you are right, I havn't noticed that have can be short alphabetic. My mistake.
@data_null__, thanks.
I have edited the post and fixed it.
Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!
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.