gpt4 book ai didi

javascript - 用常规数字替换所有出现的科学数字

转载 作者:行者123 更新时间:2023-11-29 10:36:07 25 4
gpt4 key购买 nike

我有一个大的 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不仅接受替换字符串,还接受替换函数:

You can specify a function as the second parameter. In this case, the function will be invoked after the match has been performed. The function's result (return value) will be used as the replacement string.

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

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">

将所有 float (科学或正常) chop 为整数:

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">"

关于javascript - 用常规数字替换所有出现的科学数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36101620/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com