I wrote this small utility function to nicely format monetary values:
Code
#' @title Money Format
#'
#' @description
#' The \code{money_format} function takes a numeric vector and returns formatted currency with pound sign.
#'
#' @param x numeric vector to be converted to currency
#' @param include_pound_sign A logical, defulats to \code{TRUE}.
#' @param digits An integer. Number of digits to pass to format.
#'
#' @details
#' The \code{money_format} function can be also used to pass nice UK-style SI unit formats
#' with \code{include_pound_sign = FALSE}.
#'
#' @return
#' A character vector with suffiexes and pund sign
#'
#' @import scales
#'
#' @export
#'
#' @examples
#' money_format(1e6)
money_format <- function(x, include_pound_sign = TRUE, digits = 3) {
stopifnot(is.numeric(x))
# As per: https://stackoverflow.com/a/28160474/1655567
f <-
function(x) {
div <- findInterval(x, c(1, 1e3, 1e6, 1e9, 1e12))
suffixes <- c("_", "K", "m", "bn", "T")
paste0({
if (include_pound_sign) {
intToUtf8(163)
}
}
, (
scales::unit_format(
unit = suffixes[div],
scale = switch(
suffixes[div],
"_" = 1,
K = 1e-3,
m = 1e-6,
bn = 1e-9,
"T" = 1e-12
),
sep = "",
digits = digits
)
)(x))
}
vf <- Vectorize(FUN = f, "x")
vf(x)
}
Examples
>> money_format(1e3)
[1] "£1K"
>> money_format(1e6)
[1] "£1m"
Problem
I would like to display 100
as £100
. The thing is that I'm using switch
to select suffix and I can't use ""
as variable name there. So far I was able to force "_"
as variable name, which gives:
>> money_format(10)
[1] "£10_"
but I don't want that, I want £10
. The problem is that I can't have:
scale = switch(
suffixes[div],
"" = 1,
# ^ - this fails
Desired solution
I don't want to be rewriting this function, is there some trick I could use to print out blank space for "" = 1
in my switch
statement?