Subtracting long numbers in javascript

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


const subtract = (a, b) => [a, b].map(n => [...n].reverse()).reduce((a, b) => a.reduce((r, d, i) => {
    let s = d - (b[i] || 0)
    if (s < 0) {
        s += 10
        a[i + 1]--
    }
    return '' + s + r
}, '').replace(/^0+/, ''))


Better use big-integer library for these things so as to handle all different test cases.

This is just for the a general case you can use....


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.


Jason already posted the why. For a solution, you can get a Javascript BigInt library at http://www-cs-students.stanford.edu/~tjw/jsbn/