Announcement

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

  • How to add zero before a decimal point for string

    I have string variables:

    Code:
    .2568
    .0356
    .025
    0.256
    0.5682
    Please how do I format the first three observations to have zero before the decimal point?

    Thanks

  • #2
    Please read and act on FAQ Advice #12 https://www.statalist.org/forums/help#stata

    You can't do this by changing the display format.

    What you can do is illustrated here

    Code:
    clear 
    input str6 whatever 
    .2568
    .0356
    .025
    0.256
    0.5682
    end 
    
    replace whatever = "0" + whatever if substr(whatever, 1, 1) == "." 
    
    list 
    
         +----------+
         | whatever |
         |----------|
      1. |   0.2568 |
      2. |   0.0356 |
      3. |    0.025 |
      4. |    0.256 |
      5. |   0.5682 |
         +----------+
    A more puzzling question is why this kind of data is being held as string any way.

    Comment


    • #3
      If you want to keep it a string variable, the following will do the trick:

      Code:
      replace myvar="0"+myvar if regexm(myvar,"^\.")
      This is a simple regular expression replacement where the ^ tells it to limit the search to the beginning of the string, the \ is to tell it you mean literally a "." since regular expressions interpret that as "any character". Alternatively, if you don't need the numbers as strings (which is likely the case), you can just destring and format the variable to look how you want it.

      Code:
      destring myvar, replace
      format myvar %5.3f
      You can type in -help format- to see more detail on the options here.

      Comment


      • #4
        Just an addition to #3. Since Madu Abuchi apparently prefers to have a leading zero before the decimal point, the format should be -format myvar %04.3f-.

        Comment

        Working...
        X