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: Register Now

Registration is now open for SAS Innovate 2025 , our biggest and most exciting global event of the year! Join us in Orlando, FL, May 6-9.
Sign up by Dec. 31 to get the 2024 rate of just $495.
Register now!

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.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

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