How to format a big number with different bigmarks for thousand and millions (i.e. 1'000,000) in R

Viewed 30

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.

1 Answers

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

custom_format <- function(number, tsep = ",", msep = "'") {
  # function to format thousands
  format_thousands <- function(number, tsep) {
    paste0(number %/% 1e3, tsep, number %% 1e3)
  }
  
  # function to format millions
  format_millions <- function(number, msep, tsep) {
    paste0(number %/% 1e6, msep, format_thousands(number %% 1e6, tsep))
  }
  
  # Getting number size
  number_size = dplyr::case_when(
    number %/% 1e6 > 0 ~ "millions",
    number %/% 1e3 > 0 ~ "thousands",
    TRUE ~ "other"
  )
  
  ifelse(
    number_size == "millions",
    format_millions(number, msep, tsep),
    ifelse(
      number_size == "thousands",
      format_thousands(number, tsep),
      number
      )
  )
  
}

custom_format(c(1234234, 1234234, 12345666))
#> [1] "1'234,234"  "1'234,234"  "12'345,666"

With this function you're not limited to that specific symbols, you can use others

custom_format(c(1234234, 1234234, 12345666), ",", "'")
#> [1] "1'234,234"  "1'234,234"  "12'345,666"
custom_format(c(1234234, 1234234, 12345666), '"', "'")
#> [1] "1'234\"234"  "1'234\"234"  "12'345\"666"
custom_format(c(1234234, 1234234, 12345666), '_', "-")
#> [1] "1-234_234"  "1-234_234"  "12-345_666"

Created on 2022-09-23 with reprex v2.0.2

Related