Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
R function to deal with sprintf("%.2f", ...) returning -0.00
# a function to deal with sprintf("%.2f", ...) returning -0.00
# see https://twitter.com/hspter/status/314858331598626816
f <- function(..., dig=2) {
g <- sprintf(paste0("%.", dig, "f"), ...)
z <- paste0("0.", paste(rep("0", dig), collapse=""))
g[g==paste0("-",z)] <- z
g
}
# this should return c("0.000", "0.000", "0.500", "-0.500", "-0.002")
f(c(-0.0002, 0.0002, 0.5, -0.5, -0.002), dig=3)
@hilaryparker

This comment has been minimized.

Copy link

hilaryparker commented Mar 22, 2013

This worked like a charm. Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.