Solved
Contributor
Posts: 40

# Adding zeros onto character values

data have;

input x \$;

cards;

24

1

3mn8

s27

25

;run;

Now I have to create a variable y of length=6, such as:

000024

000001

003mn8

0000s27

000025

How can I do this? Any help appreciated!

Accepted Solutions
Solution
‎05-15-2012 02:52 AM
Super User
Posts: 10,770

## Re: Adding zeros onto character values

WOW, so many brilliant solutions , Just want to add another solution.

```data have;
input x : \$4.;
cards;
24
1
3mn8
s27
25
;
run;
data want;
length x \$ 6;
set have;
xx=translate(right(x),'0',' ');
run;

```

Ksharp

All Replies
Super User
Posts: 6,761

## Re: Adding zeros onto character values

y = '000000';

substr(y, 7-length(x)) = x;

But there better not be any blank values for X, or any longer than 6 characters.

Good luck.

Super Contributor
Posts: 1,636

## Re: Adding zeros onto character values

data have;
input x \$;
cards;
24
1
3mn8
s27
25
;
data want;
set have;
do _n_=1 to 6-length(x);
x=cats('0',x);
end;
run;
proc print;run;
Obs      x

1     000024
2     000001
3     003mn8
4     000s27
5     000025

Posts: 3,167

## Re: Adding zeros onto character values

Or this:

data have;

input x \$;

cards;

24

1

3mn8

s27

25

;

data want;

set have;

x=repeat('0',6-length(x))||left(x);

run;

proc print;run;

Regards,

Haikuo

Super User
Posts: 6,761

## Re: Adding zeros onto character values

There's a pitfall using REPEAT.  It starts with your first parameter, then repeats it an ADDITIONAL number of times.  You will get one more zero than you bargained for!

Posts: 3,167

## Re: Adding zeros onto character values

Posted in reply to Astounding

Aha! Good catch! I did NOT know that. And I am sorry I did not count it either.

I guess OP should know how to modify my code to overcome this pitfall.

Haikuo

Solution
‎05-15-2012 02:52 AM
Super User
Posts: 10,770

## Re: Adding zeros onto character values

WOW, so many brilliant solutions , Just want to add another solution.

```data have;
input x : \$4.;
cards;
24
1
3mn8
s27
25
;
run;
data want;
length x \$ 6;
set have;
xx=translate(right(x),'0',' ');
run;

```

Ksharp

🔒 This topic is solved and locked.

Need further help from the community? Please ask a new question.

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