Guanhua Lu’s Web Notes

November 20, 2008

SAS: Convert Character to Numeric, Numeric to Character

Filed under: Uncategorized — Tags: , , , , , , — guanhualu @ 2:53 pm

How to Convert Character Variable to Numeric:

SAS does not allow changing the existing variable’s type. You have to define a new variable first.

There are two ways to convert an existing character variable to a numeric variable.

1.      The first is to use the INPUT function.This example uses the INPUT function to convert a character value to a numeric value and store it in another variable. The COMMA9. informat reads the value of the SALE variable, stripping the commas. The resulting value, 2115353, is stored in FMTSALE.

   data testin;

      input sale $9.;





  1. An alternative method of converting a Character variable into a Numeric (assuming all values are valid numbers) is the simple technique of multiplying by “1” as in this example:

data new; set old;



How to Convert Numeric Variable to Character:

There are also two ways to do it.

3.      The first is to use PUT function. This example uses PUT function to convert numeric data to character data. The PUT function writes values with a specified format. It takes two arguments: the name of the numeric variable and a SAS format or user-defined format for writing the data.

char_id = put(id, 7.) ;

Below are a few examples of data conversions using the PUT function:

convert numeric “oldvar”(length) to character “newvar”(length)


put function


303 (8)

newvar=put(oldvar, 3.);

303 (3)

32000 (8)

newvar=put(oldvar, dollar7.);

$32,000 (7)

366 (8)

newvar=put(oldvar, date9.);

01jan1961 (9)


4.      When creating a new character variable, you need to define (declare) the variable before doing the conversion. This can be done easily with the LENGTH statement. NOTE that because of the left-justification of string variables and the right-justification of numeric variables, it is always a good idea to make the width (format) of the string variable at least as wide as the widest numeric value in your data, and to add the LEFT function to the equation so that the values will be left-justified:

data new;

set old;

length newgroup $ 12



Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Create a free website or blog at

%d bloggers like this: