DATA Step, Macro, Functions and more

Function to remove leading zeros

Reply
N/A
Posts: 0

Function to remove leading zeros

Hi,

I need to remove leading zeros from a SAS variable. I can only read that variable as character beacuse it contains both numbers & character values in it. Is there any function which will remove only the leading zeros from the variable?

Thanks for ur help.
Savi
Super User
Posts: 5,255

Re: Function to remove leading zeros

I'm not aware of any ready made function for this, but you could use the FINDC function with the V modifier to accomplish this:

data _null_;
a='000dfsdf0';
b= substr(a,findc(a,'0','V'));
putlog _all_;
run;

/Linus
Data never sleeps
SAS Employee
Posts: 160

Re: Function to remove leading zeros

Try this small sample code
[pre]
data test;
string = '00123A0094';
name = prxchange('s/^(0*)/ /', -1, string);
run;
[/pre]
Contributor
Posts: 29

Re: Function to remove leading zeros

WOW! awesome function, thnx!
Respected Advisor
Posts: 3,887

Re: Function to remove leading zeros

@GertNissen's RegEx needs a small amendment: Remove the blank between the "/ /" as else you're replacing leading zero's with a blank instead of only removing the zeroes.

 

data test;
  string = '00123A0094';
  name = prxchange('s/^(0*)//', -1, string);
run
SAS Employee
Posts: 105

Re: Function to remove leading zeros

Hi Savi,
If the only zeroes you have are leading zeroes you can do this:

data _null_;
x='000mgfse';
y=compress(x,'0',' ');
put _all_;
run;
N/A
Posts: 0

Re: Function to remove leading zeros

* If you want the character string left aligned, this should do it. ;

data _null_;
lz = '000123';
dummy = input(lz,best12.);
lz = put(dummy,best12. -L);
put lz= ;
drop dummy;
run;
Valued Guide
Posts: 2,174

Re: Function to remove leading zeros

try[pre] if old_var =:'0'
then new_var = substr( old_var, verify( old_var,'0' ) );
else new_var = old_var ;[/pre]
Of course, there may be a more concise way.
Here is a SASlog to demonstrate[pre]49 data ;
50 input old_var $ ;
51 if old_var =:'0'
52 then new_var = substr( old_var, verify( old_var,'0' ) );
53 else new_var = old_var ;
54 put old_var= / new_var= /;
55 cards;

old_var=0`120345
new_var=`120345

old_var=asdf3450
new_var=asdf3450

old_var=00090807
new_var=90807

old_var=0zxcvbnm
new_var=zxcvbnm
NOTE: The
[/pre]
It can be achieved in a single statement with the new SAS9.2 function IFC()...[pre]76 data ;
77 input old_var $ ;
78 new_var= ifc( old_var =:'0'
79 , substr( old_var, verify( old_var,'0' ) )
80 , old_var );
81 put old_var= / new_var= /;
82 cards;

old_var=0`120345
new_var=`120345

old_var=asdf3450
new_var=asdf3450

old_var=00090807
new_var=90807

old_var=0zxcvbnm
new_var=zxcvbnm
NOTE: The
[/pre]

It helps that the (very) old function VERIFY() returns the position in a string where a character occurs that is not in the list of characters to "verify".

PeterC
Ask a Question
Discussion stats
  • 7 replies
  • 12070 views
  • 1 like
  • 7 in conversation