1

Some countries use apostrophes "'" as million marks, and commas "," for thousand marks as in 1'234,567. Is there a way to custom format numbers to do so?

I have only found answers that round numbers and add some letters as in 1.3B, or deal with this issue in javascript, which I don't speak.

Format and prettyNum documentation seem to have only a big.mark argument with no option to set different ones within the same number.

Gonzalo T F
  • 111
  • 10

1 Answers1

1

I would write my own function to do that, check the logic here.

custom_format <- function(number, msep = "'", tsep = ",") {
  number = format(number, scientific = FALSE)
  
  dplyr::case_when(
    # for millions
    nchar(number) <= 9 & nchar(number) > 6 ~
      stringr::str_replace(
        number,
        "([0-9]+)([0-9]{3})([0-9]{3})$",
        paste0("\\1", msep, "\\2", tsep, "\\3")
      ),
    nchar(number) <= 6 & nchar(number) > 3 ~
      stringr::str_replace(
        number, 
        "([0-9])([0-9]{3})$", 
        paste0("\\1", tsep, "\\2")
      ),
    nchar(number) <= 3 ~ number,
    # For Thousands
    TRUE ~ number
  )
}

number <- c(10, 1500, 1000, 1000000, 23000, 234000000)
purrr::map_chr(number, custom_format)
#> [1] "10"          "1,500"       "1,000"       "1'000,000"   "23,000"     
#> [6] "234'000,000"

Created on 2022-09-29 by the reprex package (v2.0.1)

Johan Rosa
  • 2,797
  • 10
  • 18