Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtracting long numbers in javascript

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?

like image 950
Eric Avatar asked Jan 12 '10 15:01

Eric


2 Answers

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

like image 141
Sunil Chaudhary Avatar answered Sep 27 '22 17:09

Sunil Chaudhary


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.

like image 21
Jason Orendorff Avatar answered Sep 27 '22 18:09

Jason Orendorff