-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,058
  • 6
  • 53
  • 101
coinhndp
  • 1,913
  • 5
  • 26
  • 55

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
  • 21,605
  • 3
  • 29
  • 49
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.

ruppy
  • 45
  • 7
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
  • 10,769
  • 1
  • 9
  • 29