Skip to content Skip to sidebar Skip to footer

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. I have a string with floating point numbers 'm 135.969098800748,207.1229911216347 c -0.7762491582645,-0.

Solution 1:

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) {
  returnMath.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.

Post a Comment for "Javascript Regexp - Replace All Floating Point Numbers In A String With Rounded Numbers"