Search code examples
stringstataalphanumericrecode

How to ADD decimal to alpha-numeric variable values?


I want to add decimal to alpha numeric values of my variable ucod. UCOD values are as follows: I want to add decimal point after 2 digits in a 3 digit alpha-numeric values. Kindly help whether it is possible to do this. ucod

  • .B182 >>>B18.2
  • .I251 >>>I25.1
  • .F03 >>>F03
  • .C55 >>>C55
  • .J449 >>>J44.9
  • .N390 >>>N39.0

Solution

  • If all values are exactly EITHER one letter followed by two digits OR one letter followed by three digits, and only the latter should have a decimal point after the first two digits, then this code will work for you:

    * Example generated by -dataex-. For more info, type help dataex
    clear
    input str6 varA
    ".B182"
    ".I251"
    ".F03" 
    ".C55" 
    ".J449"
    ".N390"
    end
    
    * Remove leading decimal point
    gen varB = substr(varA,2,.)
    
    * If string length is 4, take the first 3 charachters, then add a decimal,
    * and then add the remaining part of the string and 
    * then replace the value with the results
    replace varB = substr(varB,1,3) + "." + substr(varB,4,.) if strlen(varB) == 4