简体   繁体   English

javascript regexp-用舍入数字替换字符串中的所有浮点数

[英]javascript regexp - replace all floating point numbers in a string with rounded numbers

Kind of basic javascript/regexp yet i just cant get it together right now. 一种基本的javascript / regexp,但我现在无法将其组合在一起。

I have a string with floating point numbers 我有一个带浮点数的字符串

"m 135.969098800748,207.1229911216347 c -0.7762491582645,-0.2341987326806  -1.1870973239185,-1.1248369132174 -1.6826107603382,-1.6767899650268 z"

and i want to replace all floating point numbers with rounded numbers (Math.round) 我想将所有浮点数替换为四舍五入的数字(Math.round)

"m 136,207 c -1,0  1,-1 -2,-2 z"

How to do that? 怎么做?

thanks 谢谢

Use .replace and a callback. 使用.replace和回调。

var str = "m 135.969098800748,207.1229911216347 c -0.7762491582645,-0.2341987326806  -1.1870973239185,-1.1248369132174 -1.6826107603382,-1.6767899650268 z";
str.replace(/-?\d+\.\d+/g, function(x) {
  return Math.round(parseFloat(x));
})

=> "m 136,207 c -1,0  -1,-1 -2,-2 z"

Btw, there's a typo in your expected result, you're missing a - 顺便说一句,您的预期结果有误,您错过了-

"m 136,207 c -1,0  1,-1 -2,-2 z"

should be 应该

"m 136,207 c -1,0  -1,-1 -2,-2 z"

and my code above gives the correct result. 我上面的代码给出了正确的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM