Stata The Stata listserver
[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index]

Re: st: substring from large numbers


From   Joseph Coveney <[email protected]>
To   Statalist <[email protected]>
Subject   Re: st: substring from large numbers
Date   Tue, 13 Dec 2005 13:35:33 +0900

Richard Palmer-Jones wrote:

Why does:
gen str3 hhno = substr(string(hholdid),-3,3)
give me +09?
hholdid is double - format %12.0f
Well I know why - it reads the exponent. I did it by:
gen int hhno = hholdid - 1000 * int(hholdid/1000)
Also, I see one can use "tostring" which behaves correctly, and then extract
the last three characters using substr()
- but I would still like to know why.

--------------------------------------------------------------------------------

Use the format option for the -string()- function, i.e., -string(n,"%fmt")-
(the second syntax in the help file), when converting large-valued numeric
variables to string.

The first rule, though, is to start out using string, not numeric, variables
for ID numbers.

Joseph Coveney

. set obs 1
obs was 0, now 1

. generate double hholdid = 1234567890

. list

     +-----------+
     |   hholdid |
     |-----------|
  1. | 1.235e+09 |
     +-----------+

. format hholdid %12.0f

. list

     +------------+
     |    hholdid |
     |------------|
  1. | 1234567890 |
     +------------+

. gen str hhno = string(hholdid)

. list

     +-----------------------+
     |    hholdid       hhno |
     |-----------------------|
  1. | 1234567890   1.23e+09 |
     +-----------------------+

. replace hhno = substr(string(hholdid),-3,3)
(1 real change made)

. list

     +-------------------+
     |    hholdid   hhno |
     |-------------------|
  1. | 1234567890    +09 |
     +-------------------+

. replace hhno = string(hholdid, "%12.0f")
hhno was str8 now str10
(1 real change made)

. list

     +-------------------------+
     |    hholdid         hhno |
     |-------------------------|
  1. | 1234567890   1234567890 |
     +-------------------------+

. replace hhno = substr(string(hholdid, "%12.0f"),-3,3)
(1 real change made)

. list

     +-------------------+
     |    hholdid   hhno |
     |-------------------|
  1. | 1234567890    890 |
     +-------------------+

*
*   For searches and help try:
*   http://www.stata.com/support/faqs/res/findit.html
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/



© Copyright 1996–2024 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index