Contributor
Posts: 58

# return first digit of a numeric variable

Ok, I've googled this and searched the sas website and i'm just not finding the answer to this most simple of questions:

I need to return the first digit of a numeric variable into a new variable. Can someone please give me the data step i need or the command in proc sql?

Thanks!
Super User
Posts: 10,784

## Re: return first digit of a numeric variable

[pre]
data digit;
input id;
datalines;
107
204
508
359
;
run;
proc sql;
create table want as
select *,left(put(id,best20.)) length=1 as firstdigit
from digit;
quit;
[/pre]

Ksharp
Contributor
Posts: 58

## Re: return first digit of a numeric variable

Hey KSharp,
Is there a way to use this to create a numeric variable instead of a character one? or do i just need to convert it back to a numeric after i'm done?

Thanks,
cr
Super User
Posts: 13,583

## Re: return first digit of a numeric variable

> Hey KSharp,
> Is there a way to use this to create a numeric
> variable instead of a character one? or do i just
> need to convert it back to a numeric after i'm done?
>
> Thanks,
> cr

Not the best programming practice but if you leave off the length declaration the target variable will default to numeric and you'll get a numeric result and warnings in the log about conversion from string to numeric.
Super User
Posts: 10,784

## Re: return first digit of a numeric variable

Yes.You need to convert it back to a numeric after it.

Ksharp
New Contributor
Posts: 3

## Re: return first digit of a numeric variable

Hi CharlesR,
You can also make use of substr() funtion.

data have;
input id;
datalines;
107
204
508
359
;
run;
data want;
set have;
length id2 \$1;
id2 = substr(put(id,best12.),1,1);
put id2=;
run;

Thanks,
Amar Mundankar.
Super Contributor
Posts: 578

## Re: return first digit of a numeric variable

you would need to use the left function as well:

id2=substr(left(put(id,best12.)),1,1);
Contributor
Posts: 58

## Re: return first digit of a numeric variable

Thanks to everyone for the responses! Really appreciate all the help!!
Regular Contributor
Posts: 241

## Re: return first digit of a numeric variable

See an excellent solution without type conversions at sas-l:
http://www.listserv.uga.edu/cgi-bin/wa?A2=ind0001B&L=sas-l&D=0&P=30671
Super User
Posts: 10,784

## Re: return first digit of a numeric variable

That is pure mathematics way.I like it.
New Contributor
Posts: 4

## Re: return first digit of a numeric variable

This is a format problem. What you want is the first significant digit of the number.

Check David Chapman's NESUG or SUGI paper on user define formats and proc report. He shows how to create a format to show the first two significant digits. Just modify that to show the first significant digit.
Discussion stats
• 10 replies
• 12676 views
• 0 likes
• 7 in conversation