[Solved] Calculation of long number in JavaScript


The value you retrieve from the DOM is already a String, but you’re coercing it to a Number by using + in front of +lastrow. Get rid of that + and ditch the .toString() in item_no.toString().substring(2);

For addition, the max number in JavaScript is 9007199254740991. So you’ll have to do some addition on a smaller part of the number and rejoin it as a String.

This is a great article demonstrating how you can work with large numbers:

https://medium.com/@nitinpatel_20236/javascript-adding-extremely-large-numbers-and-extra-long-factorials-229b6055cb1a

There is also this library that does all the heavy lifting for you:

https://github.com/niinpatel/addVeryLargeNumbers

Basic Example

This example is a very basic example, and obviously won’t work if you add 1 to 9.

var number="00112014000002000003300008";

function incrementByOne(number) {
  var start = number.slice(0, number.length -1);
  var end = parseInt(number.slice(number.length -1));
  
  end++;
  
  console.log(start + end);
}

incrementByOne(number);

Get number from HTML (per comments discussion)

var lastrow = $('#lastrow');
var item_no = lastrow.find('.item_no').text();
console.log(typeof item_no, item_no);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="lastrow">
  <p class="item_no">00112014000002000003300008</p>
</div>

Documentation

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER

4

solved Calculation of long number in JavaScript