【问题标题】:javascript regexp - replace all floating point numbers in a string with rounded numbersjavascript regexp - 用四舍五入的数字替换字符串中的所有浮点数
【发布时间】:2013-11-09 15:14:09
【问题描述】:

一种基本的 javascript/regexp,但我现在无法将它们组合在一起。

我有一个带有浮点数的字符串

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

我想用四舍五入的数字替换所有浮点数(Math.round)

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

怎么做?

谢谢

【问题讨论】:

    标签: javascript regex


    【解决方案1】:

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

    顺便说一句,您的预期结果中有错字,您缺少-

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

    应该是

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

    我上面的代码给出了正确的结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多