Reputation: 868
I am just trying to add 1 to a big number if some conditions are met. Here is my javascript:
console.log('n1->'+n1+ ' - ' + typeof(n1) );
console.log('n2->'+n2);
if(n1 != null && n2 != n1){
console.log('adding 1');
n2 = n1 + 1;
}
console.log('n2->'+n2);
And here is the console output:
n1->443751754287812600 - number
n2->null
adding 1
n2->443751754287812600
I was expecting having n2=443751754287812601
or even n2=4437517542878126001
. Can you explain why it is not working? and how to do the sum correctly?
Thanks for your help.
Upvotes: 1
Views: 1089
Reputation: 350760
Now that BigInt exists, we can do:
let n1 = 443751754287812600n; // BigInt literal
let n2 = n1 + 1n; // Add BigInt 1
console.log(Number(n2 - n1)); // 1 (conversion to Number is only necessary in Snippet)
Upvotes: 0
Reputation: 5201
This number is too large, So what you can do is that you can use strint or some other libraries,This library lets you work with arbitrarily large integers, by storing them in strings. or you can use BigInteger.js
check this link for strint
https://github.com/rauschma/strint
Google for more
Upvotes: 1
Reputation: 382274
Numbers in JavaScript are what is often called a double in most languages : IEEE754 double precision floating point numbers.
They have a limited precision (2^53=9,007,199,254,740,992 for the biggest integer) and there you simply passed that limit.
Upvotes: 5