Brothers
Brothers

Reputation: 99

How do I add 1 to a big integer represented as a string in JavaScript?

How do I add 1 to this string in JavaScript?

var message = "12345612345678901234567890";

I want the output like this:

"12345612345678901234567891"

I tried this:

var message = "12345612345678901234567890";
message = parseInt(message);
var result = message + 1;

But parseInt returned a value in scientific notation like 1.234567896453e+25.

Upvotes: 5

Views: 5298

Answers (3)

Kamil Naja
Kamil Naja

Reputation: 6692

There is no need to use libraries (2022), you can just use JS BigInt object

let message = "12345612345678901234567890";
let messageBigInt = BigInt(message);
console.log(messageBigInt + BigInt(1)); // 12345612345678901234567891n

Upvotes: 3

Blue
Blue

Reputation: 22911

Try the big integer library BigInteger.js to add large numbers.

var message = "12345612345678901234567890";

var messageAsNumber = bigInt(message);
var messagePlusOne = messageAsNumber.add('1');

console.log(messagePlusOne.toString());
<script src="https://peterolson.github.io/BigInteger.js/BigInteger.min.js"></script>

Upvotes: 8

guest271314
guest271314

Reputation: 1

You can create an array from the string in .lengths of 3 beginning from the end of the string.

Use a pattern which checks if adding 1 would result in the index of the array as a number would sum to 1000, if true, increment previous array index by 1 and fill the current array index with "000".

The pattern below only checks and adjusts last two elements of array; the same pattern can be extended to check each index of array, to properly adjust one or more of the indexes to "000" and increment the previous index by 1.

let message1 = "12345612345678901234567890";
let message2 = "12345612345678901234567999";
let message3 = "12345612345678901234999999";

function addNumberToString(str, numToAdd, digits = []) {

  const [N, len, max] = [3, str.length, 1000];

  for (let i = -N, l = len; digits.length < len / N; i -= N, l -= N) {
    digits.unshift(str.slice(i, l));
  }

  function add(m) {
    if (+digits[digits.length - m] + numToAdd < max) {
      let n = +digits[digits.length - m];
      digits[digits.length - m] = String(Number(n + numToAdd));
    } else {
      const M = m + 1;
      if (+digits[digits.length - M] + numToAdd < max) {
        let n = +digits[digits.length - M];
        digits[digits.length - M] = String(Number(n + numToAdd));
        digits[digits.length - (M - 1)] = "0".repeat(N);
      } else {
          if (digits[digits.length - (m + 1)]) {
            digits[digits.length - (M - 1)] = "0".repeat(N);
            add(m + 1);
          }
      }
    }
    return digits.join("")
  }
  return add(1);

}

console.log(
  addNumberToString(message1, 1)   
, addNumberToString(message2, 1)
,  addNumberToString(message3, 1)
);

Upvotes: 0

Related Questions