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.
We can use gsubfn
library(gsubfn)
gsubfn("([0-9.]+)", ~format(round(as.numeric(x), 2), nsmall=2), str1)
#[1] "Hello23.90World1.12"
str1 <- "Hello23.898445World1.12212"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With