Why is q == 0 in the following script?
<script>
var start = 1234567890123456789;
var end = 1234567890123456799;
var q = end - start;
alert(q);
</script>
I would think the result should be 10. What is the correct way to subtract these two numbers?
As of January 2020, BigInt
datatype is going to be added to Javascript. The proposal is currently in Stage 4. It will enable precise calculation for number which are more than 2^53-1 (Number.MAX_SAFE_INTEGER).
BigInt has been shipped in Chrome, Node, Firefox, and is underway in Safari. Read more here.
var start = BigInt('1234567890123456789');
var end = BigInt('1234567890123456799');
var q = end - start;
alert(q)
A BigInt is created by appending n to the end of an integer literal — 10n
— or by calling the function BigInt(). It is also different from Number so 1 + 1n will fail.
You can read more about it here from MDN pages
Because numbers in JavaScript are floating-point. They have limited precision.
When JavaScript sees a very long number, it rounds it to the nearest number it can represent as a 64-bit float. In your script, start
and end
get rounded to the same value.
alert(1234567890123456789); // says: 1234567890123456800
alert(1234567890123456799); // says: 1234567890123456800
There's no built-in way to do precise arithmetic on large integers, but you can use a BigInteger library such as this one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With