round all float numbers in a string

后端 未结 3 767
轻奢々
轻奢々 2021-01-18 23:51

I am trying to replace all the float numbers in the string with the same numbers rounded to 2 decimal places. For example \"Hello23.898445World1.12212\" should

3条回答
  •  半阙折子戏
    2021-01-19 00:16

    Or using stringr:

    library(stringr)
    x <- "Hello23.898445World1.12212"
    
    r1 <- round(as.numeric(str_extract_all(x, "-*\\d+\\.*\\d*")[[1]]),2)
    # [1] 23.90  1.12
    r2 <- strsplit(gsub("\\d", "", x),"\\.")[[1]]
    # [1] "Hello" "World"
    paste0(r2, format(r1, digits = 3, trim=T), collapse = "")
    
    # [1] "Hello23.90World1.12"
    

提交回复
热议问题