Macros for SAS Application Developers
https://github.com/sasjs/core
Loading...
Searching...
No Matches
mp_aligndecimal.sas
Go to the documentation of this file.
1/**
2 @file
3 @brief Apply leading blanks to align numbers vertically in a char variable
4 @details This is particularly useful when storing numbers (as character) that
5 need to be sorted.
6
7 It works by splitting the number left and right of the decimal place, and
8 aligning it accordingly. A temporary variable is created as part of this
9 process (which is automatically dropped)
10
11 The macro can be used only in data step, eg as follows:
12
13 data _null_;
14 length myvar $50;
15 do i=1 to 1000 by 50;
16 if mod(i,2)=0 then j=ranuni(0)*i*100;
17 else j=i*100;
18
19 %mp_aligndecimal(myvar,width=7)
20
21 leading_spaces=length(myvar)-length(cats(myvar));
22 putlog +leading_spaces myvar;
23 end;
24 run;
25
26 The generated code will look something like this:
27
28 length aligndp4e49996 $7;
29 if index(myvar,'.') then do;
30 aligndp4e49996=cats(scan(myvar,1,'.'));
31 aligndp4e49996=right(aligndp4e49996);
32 myvar=aligndp4e49996!!'.'!!cats(scan(myvar,2,'.'));
33 end;
34 else do;
35 aligndp4e49996=myvar;
36 aligndp4e49996=right(aligndp4e49996);
37 myvar=aligndp4e49996;
38 end;
39 drop aligndp4e49996;
40
41 Results (myvar variable):
42
43 0.7683559324
44 122.8232796
45 99419.50552
46 42938.5143414
47 763.3799189
48 15170.606073
49 15083.285773
50 85443.198707
51 2022999.2251
52 12038.658867
53 1350582.6734
54 52777.258221
55 11723.347628
56 33101.268376
57 6181622.8603
58 7390614.0669
59 73384.537893
60 1788362.1016
61 2774586.2219
62 7998580.8415
63
64
65 @param [in] var The (data step, character) variable to modify
66 @param [in] width= (8) The number of characters BEFORE the decimal point
67
68 <h4> SAS Macros </h4>
69 @li mf_getuniquename.sas
70
71 <h4> Related Programs </h4>
72 @li mp_aligndecimal.test.sas
73
74 @version 9.2
75 @author Allan Bowe
76**/
77
78%macro mp_aligndecimal(var,width=8);
79
80 %local tmpvar;
81 %let tmpvar=%mf_getuniquename(prefix=aligndp);
82 length &tmpvar $&width;
83 if index(&var,'.') then do;
84 &tmpvar=cats(scan(&var,1,'.'));
85 &tmpvar=right(&tmpvar);
86 &var=&tmpvar!!'.'!!cats(scan(&var,2,'.'));
87 end;
88 else do;
89 &tmpvar=cats(&var);
90 &tmpvar=right(&tmpvar);
91 &var=&tmpvar;
92 end;
93 drop &tmpvar;
94
95%mend mp_aligndecimal;