phsmethods icon indicating copy to clipboard operation
phsmethods copied to clipboard

Formatting numbers as percentages (function)

Open Nic-Chr opened this issue 3 years ago • 0 comments

Opening this issue to suggest adding a function to format numbers as percentages.

format_perc <- function(x, digits = 1, nsmall = 1, round_half_up = TRUE, ...){
  if (round_half_up) {
    x <- janitor::round_half_up(x * 100, digits = digits)
    if (nsmall < digits) {
      y <- paste0(formatC(janitor::round_half_up(x, digits = nsmall), digits = nsmall, format = "f", ...), "%")
    } else {
      y <- paste0(formatC(x, digits = nsmall, format = "f", ...), "%")
    }
  } else {
    y <- paste0(formatC(round(x * 100, digits = digits), digits = nsmall, format = "f", ...), "%")
  }
  ifelse(grepl("NA", y, fixed = TRUE), NA_character_, y)
}

This uses janitor's round_half_up() by default with an argument to disable this behaviour.

Nic-Chr avatar May 22 '21 17:05 Nic-Chr