0

I've googled this a lot but I can't find any helpful functions based on my queries.

What i want is:

1.2K       ->  1,200
304.0M     ->  304,000,000
987.654B   ->  987,654,000,000

Is there any way that I can convert numbers with suffixes (K - Thousand, M - Million, B - Billion) to raw double numbers? I only found solutions to convert in the other direction.

Jannik
  • 5
  • 2
  • Is the `dplyr` tag important ... ? – Ben Bolker Aug 26 '20 at 16:33
  • Here some examples the other way around which could be useful: [this](https://stackoverflow.com/questions/28159936/format-numbers-with-million-m-and-billion-b-suffixes) & [this](https://stackoverflow.com/questions/11340444/convert-numbers-to-si-prefix). – David Arenburg Aug 26 '20 at 16:41

2 Answers2

1

Something may already exist somewhere, but I was too lazy to check ...

suffs <- c(K=1e3, M=1e6, B=1e9)
conv <- function(x) {
    nc <- nchar(x)
    suff <- substr(x,nc,nc) ## select last char
    suffval <- suffs[suff]  ## find corresponding numeric value
    num <- as.numeric(substr(x,1,nc-1))  ## select all but last char
    num*suffval
}
conv(c("1.2K","304.0M","987.654B"))

This doesn't do any checking for bad suffixes, numbers without suffixes, etc. etc..

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
1
string_vec <- c("1.2K", "304.0M", "987.654B", "1.78")

conv_df <- data.frame(
  symbol = c("", "K", "M", "B"),
  value = c(1, 1000, 1000000, 1000000000)
)

convert <- function(string_vec){
  
  data.frame(
    string_value = parse_number(string_vec),
    symbol = string_vec %>% str_sub(start = -1) %>% str_remove("[0-9]") 
  ) %>%
    left_join(conv_df, by = "symbol") %>%
    mutate(true_value = string_value * value) %>%
    pluck("true_value")
}

convert(string_vec)
det
  • 5,013
  • 1
  • 8
  • 16