将所有出现的科学数字替换为常规数字

Replace all occurrences of scientific numbers with regular numbers

本文关键字:数字 替换 常规      更新时间:2023-09-26

我有一个大的XML字符串,里面有正则和科学记数法的十进制值。我需要一种方法将所有指数值就地转换为常规表示法。

到目前为止,我已经将以下正则表达式放在一起,它抓取了指数数字的每个实例。

/-?'d+(?:'.'d*)?(?:[eE][+'-]?'d+)?/

我可以使用以下命令将它们转换为常规符号:

Number('1.255262969126037e-14').toFixed();

现在我该如何将它们放在一起;如何就地查找所有出现的科学记数法值并将其替换为常规记数法?


考虑以下输入:

<path class="arc" d="M1.3807892660386408e-14,-225.50000000000003A225.50000000000003,225.50000000000003 0 0,1 219.47657188958337,51.77146310079094L199.52415626325757,47.06496645526448A205,205 0 0,0 1.255262969126037e-14,-205Z">

我需要以下输出:

<path class="arc" d="M0,-225.50000000000003A225.50000000000003,225.50000000000003 0 0,1 219.47657188958337,51.77146310079094L199.52415626325757,47.06496645526448A205,205 0 0,0 0,-205Z">

>String.prototype.replace不仅接受替换字符串,还接受替换函数:

可以将函数指定为第二个参数。在这种情况下, 函数将在执行匹配后调用。这 函数的结果(返回值)将用作替换 字符串。

将所有科学记数法值转换为普通记数法:

input.replace(/-?'d+('.'d*)?(?:[eE][+'-]?'d+)?/g, function(match, $1) {
    // Count the number of digits after `.`,
    // then -1 to delete the last digit,
    // allowing the value to be rendered in normal notation
    var prec = $1 ? $1.length - 1 : 0; 
    // Return the number in normal notation
    return Number(match).toFixed(prec);
})
// => <path class="arc" d="M0.0000000000000138,-225.50000000000003A225.50000000000003,225.50000000000003 0 0,1 219.47657188958337,51.77146310079094L199.52415626325757,47.06496645526448A205,20‌​5 0 0,0 0.000000000000013,-205Z">

将所有浮点数(科学或正常)截断为整数:

var input = '<path class="arc" d="M1.3807892660386408e-14,-225.50000000000003A225.50000000000003,225.50000000000003 0 0,1 219.47657188958337,51.77146310079094L199.52415626325757,47.06496645526448A205,205 0 0,0 1.255262969126037e-14,-205Z">';
input.replace(/-?'d+(?:'.'d*)?(?:[eE][+'-]?'d+)?/g, function(match) {
    return Number(match).toFixed();
})
// => "<path class="arc" d="M0,-226A226,226 0 0,1 219,52L200,47A205,205 0 0,0 0,-205Z">"