Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@kbroman
Created March 21, 2013 23:04
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kbroman/5217617 to your computer and use it in GitHub Desktop.
Save kbroman/5217617 to your computer and use it in GitHub Desktop.
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
Copy link

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