Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

round all float numbers in a string

Tags:

replace

r

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.

like image 726
Alex Nevsky Avatar asked Jul 05 '16 12:07

Alex Nevsky


1 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"
like image 155
akrun Avatar answered Sep 23 '22 00:09

akrun