Twist all floating point numbers in a string

I am trying to replace all floating point numbers in a string with the same numbers, rounded to 2 decimal places. For example, "Hello23.898445World1.12212"should become "Hello23.90World1.12".

I can find the positions of the numbers gregexpr("[[:digit:]]+\\.*[[:digit:]]*", str)[[1]], but I have no idea how to replace them with my rounded originals.

+4
source share
2 answers

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"
+3
source

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
source

All Articles