BookmarkSubscribeRSS Feed
CharlesR
Calcite | Level 5
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!
10 REPLIES 10
Ksharp
Super User
[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
CharlesR
Calcite | Level 5
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
ballardw
Super User
> 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.
Ksharp
Super User
Yes.You need to convert it back to a numeric after it.


Ksharp
AmarMundankar
Calcite | Level 5
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.
DBailey
Lapis Lazuli | Level 10
you would need to use the left function as well:

id2=substr(left(put(id,best12.)),1,1);
CharlesR
Calcite | Level 5
Thanks to everyone for the responses! Really appreciate all the help!!
Ksharp
Super User
That is pure mathematics way.I like it.
david2010
Calcite | Level 5
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.

SAS Innovate 2025: Call for Content

Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!

Submit your idea!

How to Concatenate Values

Learn how use the CAT functions in SAS to join values from multiple variables into a single value.

Find more tutorials on the SAS Users YouTube channel.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

Discussion stats
  • 10 replies
  • 20003 views
  • 0 likes
  • 7 in conversation