1
votes

I am trying to convert a string variable A in Stata to a string variable B such that each observation has a fixed length. For example the string variable A is

85
01
3

and I want to convert it to another string variable B with trailing zeros in order to get length 5 for each observations

85000
01000
30000

I know that in order to put leading zeros this code works gen B= string(real(A),"%05.0f"). How should it be modified in order to get trailing zeros?

2

2 Answers

2
votes

The issue is that your new variable is not the old one with a new format, but different values altogether. One way is:

clear
set more off

*----- example data -----

input ///
str2 A
85
01
3
end

list

*------ what you want -----

// desired length of string
local len = 5

// factor
gen xdif = 10 ^ (`len' - length(A))

// new values with new format
gen B0 = real(A) * xdif
gen B = string(B0,"%0`len'.0f")

list

You can make that a one-liner, if you like.

1
votes

An alternative approach that works equally well padding strings that contain non-numeric values.

clear
set more off

*----- example data -----

input ///
str3 A
85
01
3
XYZ
"D F"
end

list

*------ what you want -----

// desired length of string
local len 5

// desired trailing character
local pad 0

// new values
gen B0 = "`pad'"*`len'
gen B1 = A+B0
generate str`len' B3 = B1

// new values in a single command
generate str`len' B = A+"`pad'"*`len'

list