How to format numeric values with leading zeros in SAS?

In SAS, the PUT function can be used to format numeric values with leading zeros. The PUT function requires a variable and a format, specifying the length of the field and the number of extra zeros. For example, PUT(var,z4.) would change a value to four digits with leading zeros. This can be used for situations like when creating data sets with identifiers that require leading zeros.


You can use the Z format option in SAS to add leading zeros to numeric values.

The following examples show how to use the Z format option in practice with the following dataset in SAS that shows the total sales made by various employees at some company:

/*create dataset*/
data my_data;
    input employee $ sales;
    datalines;
A 32
B 10
C 24
D 40
E 138
F 42
G 54
H 9
I 38
J 22
K 18.5
;
run;

/*view dataset*/
proc print data=my_data;

Example 1: Use Z Format with No Decimal Places

We can use the following Z format option to add as many leading zeros as necessary to make each value in the sales column have a length of 6:

/*use Z format to add leading zeros to values in sales column*/
proc print data=my_data;
    format sales z6.;
run;

Each value in the sales column now has as many leading zeros as necessary for it to have a length of 6.

Since we didn’t specify any value after the decimal place in z6. we told SAS not to display any values after the decimal place and to simply round each value to the nearest integer.

For example, the last value in the sales column had a value of 18.5 but was rounded to 19 and then had leading zeros added to it in order to create the final value of 000019, which has  total length of 6.

Example 2: Use Z Format with Decimal Places

We can use the following Z format option to add as many leading zeros as necessary to make each value in the sales column have a length of 10, including 1 decimal place:

/*use Z format to add leading zeros to values in sales column*/
proc print data=my_data;
    format sales z10.1;
run;

Each value in the sales column now has as many leading zeros as necessary for it to have a length of 10.

Since we used z10.1 we told SAS to display one value after the decimal place of each value.

The following tutorials explain how to perform other common tasks in SAS:

x