-3

I have the following array and I want to join it into a number

    const arr = [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]
    const digits = arr.join("") //6145390195186705543
    const digitsToNumber = +arr.join("") //6145390195186705000
    console.log(digits);
    console.log(digitsToNumber);

You can see that the join function works. However, when I try to convert it into a number, it shows a weird value. Do you guys know why it happened that way?

Teemu
  • 22,918
  • 7
  • 53
  • 106
coinhndp
  • 2,281
  • 9
  • 33
  • 64

3 Answers3

1

As stated in the comments, the value is too large for JavaScript and is truncated.

We can use BigInt to prevent this. Use with caution!

const arr = [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]

const digits = arr.join(''); 
const digitsToNumber = +arr.join(""); 
const bigDigitsToNumber = BigInt(arr.join(''));


console.log(digits);                          // 6145390195186705543
console.log(digitsToNumber);                  // 6145390195186705000
console.log(bigDigitsToNumber.toString());    // 6145390195186705543
0stone0
  • 34,288
  • 4
  • 39
  • 64
0

To convert your concatenated string into a number you could use parseInt("123") method.

const number= parseInt(digitsToNumber)

However because of your number is too big or could be bigger, Javascript can not handle that numbers which contains more than 16 digit. If you also have a problem like that you can use some external big number libraries like BigNumber.Js.

Edit: According to Teemu's comment, you could also use link native big integer handling library.

erdemgonul
  • 125
  • 1
  • 9
0

They will log different results because you are exceeding Number.MAX_SAFE_INTEGER - the highest value JS can safely compare and represent numbers.

One method to check if you are ever exceeding the limit (besides remembering the value) is Number.isSafeInteger()

Number.isSafeInteger(digitsToNumber); //false

From the docs: For larger integers, consider using the BigInt type.

Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39