舍入字符串中的所有浮点数 [英] round all float numbers in a string

查看:32
本文介绍了舍入字符串中的所有浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用四舍五入到小数点后两位的相同数字替换字符串中的所有浮点数.例如 "Hello23.898445World1.12212" 应该变成 "Hello23.90World1.12".

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".

我可以通过 gregexpr("[[:digit:]]+\\.*[[:digit:]]*", str)[[1]] 找到数字的位置,但是不知道如何用圆形原件替换它们.

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

推荐答案

我们可以使用gsubfn

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

数据

str1 <- "Hello23.898445World1.12212"

这篇关于舍入字符串中的所有浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆