Format how locals are displayed in Stata

Often I use locals to calculate something (such as the mean of a variable for a specific group) and use this in a loop (say, over groups or over years). If you, for example, want to calculate the share of observations that belong to one group (say: female==1), you could simply write

quietly count if female==1
local num_fem=r(N)'
quietly count
local share_fem=num_fem'/r(N)'
di "The share of women in the sample is: `share_fem'"

which might then return something like:

The share of women in the sample is: 0.48239049

To make the output slightly better to read, Stata allows to format the format of locals. To cut the local share_fem to only two decimals, for example, we could add the following line:

local share_fem = trim("`: display %9.3g `share_fem''")

Or, alternatively, replace the last line with

di "The share of women in the sample is: " %9.3g `share_fem'

Pro-tip: use the format %09.3g if you want to use a 0 before the period sign.

Leave a Reply