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

前端 未结 1 735
醉话见心
醉话见心 2021-01-20 04:59

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

相关标签:
1条回答
  • 2021-01-20 05:28

    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

    0 讨论(0)
提交回复
热议问题