Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • strofreal vs sprintf

    In Stata (and Mata) there are left-justified and right-justified formats for numbers. For some reason strofreal() function does not obey the change in justification while the sprintf() works as I expected (Stata 13.0). I wonder if this is a bug or is there a reason for this. Compare for illustration:

    Code:
    mata "<"+strofreal(7,"%-2.0f")+">"
     mata "<"+strofreal(7,"%2.0f")+">"
     mata sprintf("<%2.0f>",7)
     mata sprintf("<%-2.0f>",7)
    Click image for larger version

Name:	sprintf.png
Views:	1
Size:	3.3 KB
ID:	46537

    (the angle brackets are added for clarity)

    I am interested in which format will deliver the behavior with leading spaces (not zeroes)? and whether the behavior of strofreal() or sprintf() is more intuitive?

    Thank you,
    Sergiy Radyakin

  • #2
    Sergiy,

    According to the strofreal() documentation:

    Leading blanks are trimmed from the result.
    So, it's not a bug, although it's not clear what the reason is. My guess this is a philosophical choice based on the assumption (probably generally correct) that users would want a string with just a number, with no blanks. If anything, the fact that your first example still has trailing blanks might be considered a bug, in that such a philosophy would dictate that trailing blanks should also be trimmed, but perhaps the use of %-2.0f was not anticipated.

    Regards,
    Joe

    Comment


    • #3
      Dear Joe, thank you for your answer. I looked very thoroughly throw the documentation for the formats, but couldn't find sufficient explanation. With your reference I see that no matter what I do with formats, it is the strofreal() function that distorts the result and it is by design (still no idea why). As I do need leading blanks, I will have to use sprintf() as a workaround. Thank you, Sergiy.

      Comment

      Working...
      X