round all float numbers in a string

2019-06-24 02:37发布

问题:

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 become "Hello23.90World1.12".

I may find numbers' positions by gregexpr("[[:digit:]]+\\.*[[:digit:]]*", str)[[1]] but have no idea how to replace them with their rounded originals.

回答1:

We can use gsubfn

library(gsubfn)
gsubfn("([0-9.]+)", ~format(round(as.numeric(x), 2), nsmall=2), str1)
#[1] "Hello23.90World1.12"

data

str1 <- "Hello23.898445World1.12212"


回答2:

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"


回答3:

Solution using no package for the string manipulation:

Also credits to @akrun format(., nsmall=2) is the trick in this solution.

Input string

stringi <- "Hello23.898445World1.12212"

Set number of decimal places

dp <- 2 #decimal places

Calculate

strsplit(x = stringi,split = "(?<=[^0-9.])(?=\\d)|(?<=\\d)(?=[^0-9.])",perl=T) %>%
    unlist %>% 
    lapply(function(x){if(!is.na(as.numeric(x)))x<-round(as.numeric(x),dp)%>%format(nsmall=dp);x}) %>%
    paste(collapse="")

Result:

#[1] "Hello23.90World1.12"


标签: r replace