1

Kind of basic javascript/regexp yet i just cant get it together right now.

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)

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

How to do that?

thanks

dorjeduck
  • 7,624
  • 11
  • 52
  • 66

1 Answers1

4

Use .replace and a callback.

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.

Dogbert
  • 212,659
  • 41
  • 396
  • 397