Bookmark and Share

Notice: On March 31, it was announced that Statalist is moving from an email list to a forum. The old list will shut down on April 23, and its replacement, statalist.org is already up and running.


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: st: SV: leading zeros in string format


From   Nick Cox <njcoxstata@gmail.com>
To   statalist@hsphsun2.harvard.edu
Subject   Re: st: SV: leading zeros in string format
Date   Fri, 8 Feb 2013 20:34:21 +0000

Another solution:

gen newstring = substr("0000000", 1, 7 - length(oldvar)) + oldvar

For completeness, note that -format %07.0f- attempts to apply a
numeric format, which is out of order for a string variable.

Nick

On Fri, Feb 8, 2013 at 8:01 PM, Michael Stewart
<michaelstewartresearch@gmail.com> wrote:

gen newstring = string(real(oldvar),"%07.0f")==>works

 On Fri, Feb 8, 2013 at 2:51 PM, Rebecca Pope <rebecca.a.pope@gmail.com> wrote:

>> That's because you're starting with a string... Petter's code works
>> fine with one modification:
>>
>> gen newstring = string(real(oldvar),"%07.0f")
>>
>>
>>
>> On Fri, Feb 8, 2013 at 1:45 PM, Michael Stewart
>> <michaelstewartresearch@gmail.com> wrote:
>>> I have tried it and get
>>>
>>> type mismatch
>>> r(109);
>>>
>>>
>>> On Fri, Feb 8, 2013 at 2:41 PM, Petter Berg <pbe@copenhageneconomics.com> wrote:
>>>> Mike if you have a fixed string length (in this case of 7) and just want to fill up with zeros you can use:
>>>> gen newstring  = string(oldvar,"%07.0f")
>>>>
>>>> Best,
>>>> Petter
>>>> ________________________________________
>>>> Från: owner-statalist@hsphsun2.harvard.edu [owner-statalist@hsphsun2.harvard.edu] f&#246;r Michael Stewart [michaelstewartresearch@gmail.com]
>>>> Skickat: den 8 februari 2013 20:24
>>>> Till: statalist@hsphsun2.harvard.edu
>>>> Ämne: st: leading zeros in string format
>>>>
>>>> HI
>>>> I am trying to convert a string  variable to a string variable with
>>>> fixed numbers
>>>>
>>>> My string variable has following observations:
>>>> 1223435
>>>> 34567
>>>> 345
>>>>
>>>> I want to convert it to another string variable with leading zeros
>>>> 1223435
>>>> 0034567
>>>> 0000345
>>>>
>>>> format var "%07.0f" didnt work

*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   http://www.stata.com/support/faqs/resources/statalist-faq/
*   http://www.ats.ucla.edu/stat/stata/


© Copyright 1996–2014 StataCorp LP   |   Terms of use   |   Privacy   |   Contact us   |   Site index