如何使用Reg Exp对字符串中的所有数字进行舍入?

时间:2018-06-10 05:10:15

标签: javascript regex

我正在研究SVG minifier。我满足了这种需求。 SVG中包含很多数字作为字符串,例如:

123.66 12.50 162.9873 23.67

我想将它们改为:

124 13 163 24

我所尝试的是首先删除长数字:

// reduce the decimal to only 1 digit
source=source.replace(/(\d\.\d)\d+/g ,'$1');

然后,我尝试了

source=source.replace(/(\d)\.1/g,'$1');
source=source.replace(/(\d)\.2/g,'$1');
source=source.replace(/(\d)\.3/g,'$1');
source=source.replace(/(\d)\.4/g,'$1');
如上所示,使用6.17.2替换67非常简单。但是,我怎样才能将6.8变成79.9变成10

我试过这个,但没有工作:

source=source.replace(/(\d)\.6/g,Number('$1')+1);
source=source.replace(/(\d)\.7/g,Number('$1')+1);
source=source.replace(/(\d)\.8/g,Number('$1')+1);
source=source.replace(/(\d)\.9/g,Number('$1')+1);

有关于此的任何提示吗?

2 个答案:

答案 0 :(得分:4)

确保也选择小数(当它们存在时),然后传递一个函数作为round的替换者:



const str = '123.66 12.50 162.9873 23.67 23.22';
console.log(
  str.replace(/\d+\.\d+/g, Math.round)
);




答案 1 :(得分:2)

只需使用Math.round($i),无需将数据作为字符串处理。整数更适合您的用例。