Skip to content
Prev 278812 / 398502 Next

format numbers without leading or trailing 0s

You may also want to deal with a possible
leading negative sign:

  > lambda <- c(0, 0.005, 0.01, 0.02, 0.04, 0.08,
               -0.005, -0.01, -0.02, -0.04, -0.08, 1000)
  > gsub("^0(\\..*[^0])0*$","\\1", lambda)
   [1] "0"      ".005"   ".01"    ".02"    ".04"    ".08"   
   [7] "-0.005" "-0.01"  "-0.02"  "-0.04"  "-0.08"  "1000"  
  > gsub("^(-)?0(\\..*[^0])0*$","\\1\\2", lambda) # -0. -> .
   [1] "0"     ".005"  ".01"   ".02"   ".04"   ".08"   "-.005"
   [8] "-.01"  "-.02"  "-.04"  "-.08"  "1000"

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com