DATA Step, Macro, Functions and more

input without knowing length

Reply
Contributor
Posts: 41

input without knowing length

Hi,

 

 I want to convert a character A to numberic B

I use the input() function. But you can only use it if you know the length of A.

A = input(B,8.2)

But I don't know if it is 8.2 or whatever.

Do you know how I can manage it?

Super User
Posts: 10,532

Re: input without knowing length

Use the best. format:

data test;
input b :$32.;
a = input(b,best32.);
format a best32.;
cards;
123456.78
12345678912.22
1.12345678905
3.14159265358979323846
;
run;

proc print data=test noobs;
run;

Result:

b                                                        a

123456.78                                        123456.78
12345678912.22                              12345678912.22
1.12345678905                                1.12345678905
3.14159265358979323846                    3.14159265358979

Note how the Pi example shows the limits of numeric precision in SAS.

---------------------------------------------------------------------------------------------
Maxims of Maximally Efficient SAS Programmers
How to convert datasets to data steps
How to post code
Super User
Super User
Posts: 9,813

Re: input without knowing length

I would question why you do not know your data, seeing as that is the fundamental basis for programming with?  What if it contains non-numerics, or signs/percentages, what format should the output variable have etc.

Regular Contributor
Posts: 164

Re: input without knowing length

Hi,

 

a pragmatic approach could be to perform a reconversion check and issue warnings to your log in case of conversion failure.

Something like that:

 

if strip(put(a,best32.)) ne b then put 'W' 'ARNING: conversion issue please check' a= b=;

 

________________________

- Cheers -

Valued Guide
Posts: 626

Re: input without knowing length

Another way to verify that the char var has been converted successfully, uses the double ? modifier in the input function. Thanks to @KurtBremser for provding example data ;-)

 

data test;
input b :$32.;
a = input(b, ?? best32.);
if missing(a) and not missing(b) then put 'WARNING: Failed to convert ' b 'Check obs' _n_= ;
format a best32.;
cards;
123456.78
12345678912.22
1.12345678905
bob
3.14159265358979323846
;
run;

proc print data=test noobs;
run;
Ask a Question
Discussion stats
  • 4 replies
  • 111 views
  • 0 likes
  • 5 in conversation