Bookmark and Share

Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at statalist.org.


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

st: Converting numbers to string: %f versus %g


From   Joe Canner <[email protected]>
To   "[email protected]" <[email protected]>
Subject   st: Converting numbers to string: %f versus %g
Date   Thu, 22 Aug 2013 16:43:02 +0000

Dear Stata community,

According to the (Stata 12) help for -format-: " %g differs from %f in that (1) it decides how many digits to display to the right of the decimal point, and (2) it will switch to a %e format if the number is too large or  too small."

However, there seem to be more differences than this.  I have a numeric (long) variable with a date in the form YYYYMMDD that I want to convert to a date variable. I did the following:

. gen DOS=date(string(DateofService,"%8.0g"),"YMD")

This didn't work, because the -string()- function returned the same value ("2.0e+07") regardless of the value of DateofService.  This suggests that the %g format thinks the number is too large for the format. This can be fixed with one of the following:

. gen DOS=date(string(DateofService,"%10.0g"),"YMD")
. gen DOS=date(string(DateofService,"%8.0f"),"YMD")

My question is this: why does %f work with the right number of digits (8), but %g only works if you overstate the number of digits?  Is the required number always two more than the actual number of digits?

This is mostly a curiosity question, but it sometimes trips me up when I instinctively/mindlessly choose %8.0g and then wonder why my code isn't working.  I also sometimes forget the format and I wonder why -string()- can't guess the correct format, but that is another story...

(And, yes, I recently became aware of Nick Cox's -todate- program and will probably use that from now on.)

Thanks,
Joe Canner
Johns Hopkins University School of Medicine

*
*   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–2018 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   Site index