Announcement

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

  • How to change the format of numbers stored in a local macro?

    Dear Statalist,

    I am trying to format the number stored in a local macro using the string(n, s) function. Here is my code:
    Code:
    version 17.0
    quietly: count // Store total no. of pts to scalar
    
    scalar SC_total = r(N)
    
    local ML_total = string(SC_total, "%9.0fc")
    
    display `ML_total'
    
    3 274
    The expected output of display command is 3,274; however, it appeared without coma, like this 3 274.

    Please help me solve this issue.


    Thank you
    Abdullah
    Sincerely regards,
    Abdullah Algarni
    [email protected]

  • #2
    What you see is down to what display is doing as invoked by you; it's about more than the contents of the local macro.

    A local macro contains text -- a character string -- and it's up to the user what that text should be. It could be numeric characters, but a local macro neither knows nor cares that it holds a number; that is your view as a user or programmer when the text is indeed numeric characters.

    Let's consider what display does -- as part of what it does is evaluate what is fed to it, not just echo it. An example to make this obvious

    Code:
    . local foo "2 + 2"
    
    . display `foo'
    4
    
    . display "`foo'"
    2 + 2
    In that example, and often, there is a noticeable difference between evaluating the contents of a local macro and echoing its contents. You inhibit or limit evaluation by using " ".

    In your case it's the same difference, but your example is more subtle.

    Code:
    . local ML_total = string(3274, "%9.0fc")
    
    . display `ML_total'
    3 274
    
    . display "`ML_total'"
    3,274
    In this case Stata could see in what you presented just two numbers separated by a comma, not one number with a comma separator.

    Again, the local macro carries no awareness of the history of its contents, and neither the local macro nor Stata generally senses your view, that you are using it to store a number.
    Last edited by Nick Cox; 26 Mar 2023, 00:59.

    Comment


    • #3
      Thank you so much Nick Cox; it works nicely!

      Please allow me to acknowledge you upon publication of my research. Your posts help me a lot!!
      Sincerely regards,
      Abdullah Algarni
      [email protected]

      Comment


      • #4
        Thanks for that. You don't need my permission to acknowledge me!

        Comment

        Working...
        X