0

I'm stuck in small problem where I'm trying to convert String to number but that String number is huge due to which it is not properly converting to number type.

str = "6145390195186705543"
num = Number(str)
digits = [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]
let str = String(Number(digits.join(''))+1).split('') 

after performing above operation the value of num is 6145390195186705000 which is not what I was expecting. It should be 6145390195186705543.

It would be very helpful if someone can explain this and tell if there is any alternative way.

  • I have tried parseInt() and '+' as well but nothing is working.
14
  • 1
    JavaScript numbers have a limited ability to represent large values with complete accuracy, and your value exceeds that limit. Commented May 21, 2021 at 14:21
  • 4
    You can look into using BigInts, BigInt("6145390195186705543") Commented May 21, 2021 at 14:21
  • 3
    Also it would be helpful to know why you want that value as a number. Commented May 21, 2021 at 14:22
  • 1
    @PoojaKushwah then you're doing it incorrectly: BigInt("6145390195186705543") returns the correct value. Commented May 21, 2021 at 14:26
  • 1
    It is still not usefull. Commented May 21, 2021 at 14:34

2 Answers 2

0

If you want to increment an array of integer values, you can join the digits and pass it to the BigInt constructor. After it is a BigInt, you can add 1n. Once you have added the value, you can stringify the value and split it. Lastly, you can map each digit back into an integer.

const digits = [6, 1, 4, 5, 3, 9, 0, 1, 9, 5, 1, 8, 6, 7, 0, 5, 5, 4, 3];
const str = (BigInt(digits.join('')) + 1n).toString().split('').map(digit => +digit);
console.log(JSON.stringify(str)); // [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,4]

Here is the code above, modified into a function:

const numArrayAdd = (bigIntSource, bigIntAmount) =>
  (BigInt(bigIntSource.join('')) + bigIntAmount)
    .toString().split('').map(digit => +digit);

const digits = [6, 1, 4, 5, 3, 9, 0, 1, 9, 5, 1, 8, 6, 7, 0, 5, 5, 4, 3];
const str = numArrayAdd(digits, 1n);

console.log(JSON.stringify(str)); // [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,4]

Sign up to request clarification or add additional context in comments.

Comments

-1

you can add just a + right before that variable

a = "6145390195186705543"
b = +a // b type is number
console.log(b);

here is a good example about that https://youtu.be/Vdk18Du3AVI?t=61

2 Comments

you should provide details with some example.
I've converted your code to a runnable snippet to show you that your answer is wrong. The type of b is number, but it's the wrong number.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.