Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace all occurrences of scientific numbers with regular numbers

I've got a large XML string with decimal values in regular and scientific notation. I need a way to convert all the exponential values to regular notation in-place.

So far I've put together the following Regex which grabs every instance of a exponential number.

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

And I can convert those to regular notation using:

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

Now how do I put it all together; How do I find and replace all occurrences of scientific notation values with regular notation, in-place?


Considering the following 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">

I need the following output:

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

like image 783
Robin Rodricks Avatar asked Jan 22 '26 16:01

Robin Rodricks


1 Answers

String.prototype.replace accepts not only replacement string, but also accepts replacement function:

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.

To convert all scientific notation values to normal notation:

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

To truncate all floats (scientific or normal) into integers:

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">"
like image 172
falsetru Avatar answered Jan 25 '26 09:01

falsetru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!