Ilja
Ilja

Reputation: 46499

Converting strings like 86.678, 1.12517, 0.61457 to numbers and increment/decrement last 3 digits

I'm trying to figure out a way to convert strings like 86.678, 1.12517, 0.61457 to numbers, without loosing any decimal point information and amount of numbers.

numbers are different in nature, but I need a way to figure out how to increment/decrement last 2 digits of each such number by 30 so for example if I want to increment 86.678 it would become 86.708 I'm having trouble figuring this out as each time there is different amount of numbers after period . but there is always at least 3, also there will be cases like 89.990 where numbers will need to grow so 90.020 will be new one, same applies to decrement.

Upvotes: 1

Views: 48

Answers (1)

tadman
tadman

Reputation: 211670

This is pretty messy and ugly, but for well formed data it should work.

function incrementalize(value) {
  return parseFloat(value) +
    parseFloat(value.replace(/\d/g, 0).replace(/00$/, '30'));
}

The first regular expression here zeroes out everything, so 123.4567 becomes 000.0000, and then the trailing pair of zeroes are switched out, so you get 000.0030. That's added to your original value.

Note that when adding numbers with fractional values, the inherent imprecision of IEEE-754 double-precision numbers can show up. It does, for instance, with your 0.61457 + 0.00030 example.

Live Example:

test(86.678);
test(1.12517);
test(0.61457);
test(0.0123);
test(0.9999);

function incrementalize(value) {
  return parseFloat(value) +
    parseFloat(value.replace(/\d/g, 0).replace(/00$/, '30'));
}

function test(num) {
  var newNum = incrementalize(String(num));
  snippet.log(num + " => " + newNum);
}
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

Update: To keep the precision in the initial value, using the sprintf-js library:

function incrementalize(value) {
  return sprintf(
    '%.' + value.split(/\./)[1].length + 'f', 
    parseFloat(value) +
      parseFloat(value.replace(/\d/g, 0).replace(/00$/, '30'))
  );
}

Upvotes: 4

Related Questions