Skip to content

Instantly share code, notes, and snippets.

@DeepanshKhurana
Last active March 31, 2023 15:23
Show Gist options
  • Save DeepanshKhurana/fa917b5b881cd57cef65bcb8cbd15668 to your computer and use it in GitHub Desktop.
Save DeepanshKhurana/fa917b5b881cd57cef65bcb8cbd15668 to your computer and use it in GitHub Desktop.
Format Prices
#' @export
#'
true_round <- function(number, digits) {
number <- as.numeric(number)
posneg <- sign(number)
number <- abs(number) * 10^digits
number <- number + 0.5 + sqrt(.Machine$double.eps)
number <- trunc(number)
number <- number / 10 ^ digits
number * posneg
}
#' @export
#'
#' @description function to format price/change values
#' @param value the value to format
#' @param round the digits to round till
#' @param format the number format "d" or "f"
#' @param big the separator for big values, default ","
#' @return character url for the sheet for the user
#'
format_price <- function(value, round = 2, format = "f", big = ",") {
formatC(
as.numeric(
as.character(true_round(value, round))),
digits = round,
format = format,
big.mark = big
)
}
#' @export
#'
shorten_price <- function(value) {
value <- as.numeric(format_price(value = value, big = ""))
dplyr::case_when(
value < 1e3 ~ as.character(value),
value < 1e6 ~ paste0(as.character(true_round(value / 1e3, 1)), "K"),
value < 1e9 ~ paste0(as.character(true_round(value / 1e6, 1)), "M"),
TRUE ~ paste0(as.character(true_round(value / 1e9, 1)), "B")
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment