Quartz | Level 8

I have a variable  that is string but contains all numeric values. Examples of values include: 51, 200, 10511. I want to keep this a string variable, but have leading 0s that make each value 6 characters--specifically, such that the former values become 000051, 000200, and 010511. Can anyone help think of an elegant way to do this?

1 ACCEPTED SOLUTION

Accepted Solutions
Super User

``string = put(input(string,best.),z6.-l);``

The -l makes it left-aligned (no leading blanks).

6 REPLIES 6
Diamond | Level 26

I have a variable  that is string but contains all numeric values.

This is really poorly worded. A SAS variable is either numeric or character. It doesn't matter if it "contains all numeric values", it still can be either numeric or character.

Assuming you mean your variable is NUMERIC:

Use the Z. format. Example:

``````data a;
y=50232;
z=put(y,z6.);
run;``````

--
Paige Miller
Quartz | Level 8

Sorry--I meant that my variable is character (although  each value contains only digits). I want to make it such that they all have a length of 6, by adding leading 0s to those with a length that has fewer than 6 characters (which is all values). I want the resultant variable to remain character.

Super User

``string = put(input(string,best.),z6.-l);``

The -l makes it left-aligned (no leading blanks).

Barite | Level 11

`data want;  length z \$6;  do z = '1', '22', '333', '4444', '55555', '666666', 'A';    zs = substr('000000' || left(z), length(left(z))+1);    output;  end;run; `
Super User

This is a frequently asked question.

If you are positive the string form valid integers of less than 15 digits then you can first convert the string to a number and convert it back to string using the Z format so that leading zeros are written.  Integers longer than that cannot be continuously exactly represented as numbers in SAS because it use floating point numbers.  The INPUT() function doesn't care if you use too long a width on the informat and the normal numeric informat has a maximum width of 32.

``string=put(input(string,32.),Z6.);``

Otherwise calculate the length and prefix the needed number of 0 digits. There are a lots of ways to do that. Here is one using the REPEAT() function to generate the string of zeros that is pretty easy to understand. If the length is already 6 (or greater) then you don't need any extra characters. Otherwise you will need to add (6-length of the string) number of zeros. The repeat function count argument requires 1 less than the length you want (think of it as the number or EXTRA times to repeat the pattern).

``if length(string)<6 then string=cats(repeat('0',6-length(string)-1),string);``

Meteorite | Level 14

``string=translate(right(string),'0',' ');``
``string=translate(right(substr(string,1,6)),'0',' ');``