What's the best way to format a numeric so that it does NOT show leading zero. For example:
test = .006
sprintf/format/formatC( ??? ) # should result in ".006"
Join Stack Overflow to learn, share knowledge, and build your career.
What's the best way to format a numeric so that it does NOT show leading zero. For example:
test = .006
sprintf/format/formatC( ??? ) # should result in ".006"
You can always fix it up yourself with regular expression search-and-replace:
library(stringr)
test = .006
str_replace(as.character(test), "^0\\.", ".")
Not the most elegant answer, but it works. Substitute whatever string conversion you like for as.character
, such as sprintf
with your preferred floating point format.
I believe I answered this once before but can't find it. You cannot tell sprintf()
et al about a format that drops the leading zero ... so you have to do it yourself, eg via substring()
:
R> val <- 0.006
R> aa <- substring(sprintf("%4.3f", val), 2)
R> aa
[1] ".006"
R>
substring(as.character(val), 2)
which does not need anything but base R, and is likely "faster" (not that it matters) than a regexp solution.
– Dirk Eddelbuettel
Nov 13 '12 at 0:50
f <- function(x) gsub("^(\\s*[+|-]?)0\\.", "\\1.", as.character(x))
f(0.006)
# ".006"
f(-0.006)
# "-.006"
f("+0.006")
# "+.006"
f(" 0.006")
# " .006"
f(10.05)
# "10.05"