Reputation: 1713
When we convert a numeric to character , we should use a numeric format like the following
data test ;
prodID = 001 ;
result = put(prodID , 1.) ;
run ;
proc print ;
run ;
I also tried to use a character format $1.
, and it also worked
data test ;
prodID = 001 ;
result = put(prodID , $1.) ; *I am using $1. here ;
run ;
proc print ;
run ;
Question is why did the second code work ? It was not supposed to work . Should we use a numeric or character format or it does not matter ?
Upvotes: 4
Views: 90168
Reputation: 13
To convert a character variable to a numeric variable, you use the INPUT() function (which uses informats).
newvar_num = INPUT(oldvar_char, informat)
The INPUT() function is similar to reading external data using the INPUT statement. The informat tells SAS how to read the data, and it should be read as numeric. When converting from character to numeric, the informat must be the type you are converting to, so numeric.
To convert a numeric variable to a character variable, you use the PUT() function (which uses formats).
newvar_char = PUT(oldvar_num, format)
The PUT() function is similar to writing out data using the PUT statement. The format tells SAS how to output or store the data. In the PUT() function, the format must be the same type as the source variable (oldvar_num), so numeric.
The PUT() function can also be used to convert a character variable to another character variable, with a character format. See examples A and C: https://blogs.sas.com/content/sgf/2015/05/01/converting-variable-types-do-i-use-put-or-input/.
The source variable of INPUT() function must always be character, the output can be character or numeric. The output of PUT() function is always character, the input can be character or numeric.
A good explanation of informats and formats can be found here: https://libguides.library.kent.edu/SAS/Informats-Formats.
Upvotes: 1
Reputation: 739
You do get a warning with the second code:
WARNING: Variable prodID has already been defined as numeric.
That's because you are applying a character format to a numeric variable But the result of the put function is always character.
Upvotes: 4