lmngn23
lmngn23

Reputation: 521

Issue with combining large array of numbers into one single number

I am trying to convert an array of numbers into one single number, for example

[1,2,3] to 123. 

However, my code can't handle big arrays since it can’t return exact number. Such as

[6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3] returns 6145390195186705000

Is there any way that I could properly convert into a single number.I would really appreciate any help.

var integer = 0;
var digits = [1,2,3,4]
//combine array of digits into int
digits.forEach((num,index,self) => {
    integer += num * Math.pow(10,self.length-index-1)
});

Upvotes: 1

Views: 1002

Answers (3)

Sumit Gautam
Sumit Gautam

Reputation: 49

You can use JavaScript Array join() Method and parse it into integer. Example: parseInt([6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5].join('')) results: 6145390195186705

Edited: Use BigInt instead of parseInt , but it works only on chrome browser.

Upvotes: 2

Adrian Pop
Adrian Pop

Reputation: 1967

The biggest integer value javacript can hold is +/- 9007199254740991. Note that the bitwise operators and shift operators operate on 32-bit ints, so in that case, the max safe integer is 2^31-1, or 2147483647.

In my opinion, you can choose one of the following:

  • store the numbers as strings and manipulate them as numbers; you might have to implement special functions to add/subtract/multiply/divide them (these are classic algorithmic problems)

  • use the BigInt; BigInts are a new numeric primitive in JavaScript that can represent integers with arbitrary precision. With BigInts, you can safely store and operate on large integers even beyond the safe integer limit. Unfortunately, they work only with Chrome right now. If you want to work with other browsers, you might check this or even this if you work with angularjs or nodejs.

Try the following code in the Chrome's console:

let x = BigInt([6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3].join(''));
console.log(x);

This will print 6145390195186705543n. The n suffix marks that it is a big integer.

Cheers!

Upvotes: 3

Sandesh Gupta
Sandesh Gupta

Reputation: 1195

The largest number possible in Javascript is +/- 9007199254740991

Use BigInt. Join all numbers as a string and pass it in BigInt global function to convert it into int

var integer = 0;
var digits = [1,2,3,4]
//combine array of digits into int
digits.forEach((num,index,self) => {
    integer += num;
});
integer= BigInt(integer);

Note : Works only on Chrome as of now. You can use othee libraries like BigInteger.js or MathJS

Upvotes: 1

Related Questions