Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add leading zeros to character field in SAS? [closed]

Tags:

sas

I trying to figure out the following: I have SAS dataset 'ids' with character variable with different length such as idnum3, idnum897 or idnum2342345. Need to create each ID with the same length and add leading zeros to have soething like '000000idnum3','0000idnum897', idnum2342345. I tried many options but it seems nothing works. Any suggestions please. Thanks!

like image 290
Marla_learning_sas Avatar asked May 23 '16 18:05

Marla_learning_sas


1 Answers

Two general approaches are useful here.

First, if the field is entirely numeric, you use the Zw.d format.

idnum=put(input(idnum,8.),z8.);

If it's not entirely numeric, then you use repeat() to generate the zeros. Use length() to find out how many you need. Repeat takes two arguments - the character to be repeated, and the number of repeats to add to the original. That number will be one less than the intuitive number: repeat('0',3) = 0000.

So:

  if length(idnum) lt 8 then idnum = cats(repeat('0',8-1-length(idnum)),idnum);

Make sure your ID number variable has enough length to fit the full ID, also, or this won't work.

Longer example:

data have;
input idnum $8.;
datalines;
idn2
idn234
idn23456
;;;;
run;

data want;
  set have;
  if length(idnum) lt 8 then idnum = cats(repeat('0',8-1-length(idnum)),idnum);
run;
like image 93
Joe Avatar answered Oct 09 '22 04:10

Joe