SAS: How to Use Z Format to Add Leading Zeros to Values


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.

Also note that the total length of 10 includes the decimal point and the value after the decimal point.

Additional Resources

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

SAS: How to Display Values in Dollar Format
SAS: How to Display Values in Percent Format
SAS: How to Display Values in Time Format

Leave a Reply

Your email address will not be published. Required fields are marked *