round all float numbers in a string

后端 未结 3 761
轻奢々
轻奢々 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条回答
  •  Happy的楠姐
    2021-01-19 00:38

    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"
    

提交回复
热议问题