Search code examples
javascriptmathrounding-error

Is it possible to achieve arbitrary-precision arithmetic with no rounding issues in JavaScript?


I've tried big.js, bignumber.js, and decimal.js; they all work reasonably well up to a certain point, but fall short when I need to do arbitrary-precision calculations with large enough numbers of "odd" digits (my current test case is 31435517643980 * (1 / 31435517643980) === 1). I am open to any solution that allows me to process expressions like this, including calls to an external API. I'm currently looking at Wolfram|Alpha's API, but the 2000 calls/month limit is a restriction I'd like to avoid, because my application is going to be making quite a few calls.

If this is the wrong SE site for this question, please let me know and/or move it.


Solution

  • Possibly the most common way to do this is simply multiply both numbers by the same multiplier to make them have no decimals, and then do the operation, then divide again. Here's a crude implementation:

    function getDigits(n){
        return n.toString().substring(n.toString().indexOf('.')+1).length;
    }
    function xNums(n1,n2){
        var highRes=(n1*Math.pow(10,getDigits(n1))*(n2*Math.pow(10,getDigits(n2))));
        return highRes/Math.pow(10,getDigits(n1))/Math.pow(10,getDigits(n2));
    }
    

    Then, run xNums(31435517643980,(1 / 31435517643980))===1. Works for me in Chrome