Converting variable types—use PUT() or INPUT()?

How many times have you had a need to convert between variable types such as converting character to numeric or numeric to character?  For example, what if you have a character variable with numeric values but you need to perform some calculations?  Or, if you have a numeric variable but you need to concatenate it to a character variable?  If you are like most SAS programmers, you need to use PUT() and INPUT() at least once to complete these tasks.

The answer to the question "Do I use PUT() or INPUT()?" depends on what your target variable type is and what your source variable type and data are. Below are three questions to consider:

Is your target variable character or numeric?

Is your source variable character or numeric?

If your source variable is character, is your data value character or numeric?

Based on your answers to the three questions above, you can identify whether PUT() or INPUT() comes first. Keep these four rules in mind when writing your SAS statements:

PUT() always creates character variables

INPUT() can create character or numeric variables based on the informat

The source format must match the source variable type in PUT()

The source variable type for INPUT() must always be character variables

The following examples show how to use these rules to convert from character/numeric or  numeric/character:

A  PUT() converts character variable to another character variable.

B  PUT() converts numeric variable to a character variable with numeric value.

C  PUT() converts character variable with a user defined format to another character variable.

D  INPUT() converts character variable with numeric value and informat to a numeric variable.

E  INPUT() converts character variable with numeric value and informat to a character variable.

F  INPUT() converts character variable with numeric value and informat to a numeric variable.

Function Call | Raw Type | Raw Value | Returned Type | Returned Value
A  PUT(name, $10.); | char, char format | ‘Richard’ | char always | ‘Richard   ’
B  PUT(age, 4.); | num, num format | 30 | char always | ‘  30’
C  PUT(name, $nickname.); | char, char format | ‘Richard’ | char always | ‘Rick’
D  INPUT(agechar, 4.); | char always | ‘30’ | num, num informat | 30
E  INPUT(agechar, $4.); | char always | ‘30’ | char, char informat | ‘  30’
F  INPUT(cost,comma7.); | char always | ‘100,541’ | num, num informat | 100541

WANT MORE GREAT INSIGHTS MONTHLY? | SUBSCRIBE TO THE SAS TECH REPORT
Converting variable types—use PUT() or INPUT()? was published on SAS Users.