1

I am trying to subtract two numbers with more decimals. But it is rounding up. How can I use BigNumber to make sure the numbers are not rounded and the calculation is precise.

const myObj = {
  total: 5000000,
  filled: 4999999.9999999996870756
};

const total = new BigNumber(myObj.total);
const filled = new BigNumber(myObj.filled);
const remaining = total.minus(filled);
console.log(total, filled, remaining);

if(remaining === 0.0000000003129244) console.log("remaining  calculation is correct")
else console.log("incorrect calculation")
<script src="https://cdnjs.cloudflare.com/ajax/libs/bignumber.js/8.0.2/bignumber.min.js" integrity="sha512-7UzDjRNKHpQnkh1Wf1l6i/OPINS9P2DDzTwQNX79JxfbInCXGpgI1RPb3ZD+uTP3O5X7Ke4e0+cxt2TxV7n0qQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
Kiran Dash
  • 4,816
  • 12
  • 53
  • 84

1 Answers1

5

first you need to define string variables to not rounding it up. after that for comparing values of bigNumber it's better to use 'comparedTo' refer to documents

const myObj = {
  total: '5000000',
  filled: '4999999.9999999996870756'
};

const total = new BigNumber(myObj.total);
const filled = new BigNumber(myObj.filled);
const remaining = total.minus(filled);
console.log('total',total);
console.log('filled',filled);
console.log('remaining', remaining);

if(remaining.comparedTo(0.0000000003129244) === 0) console.log("remaining  calculation is correct")
else console.log("incorrect calculation")
<script src="https://cdnjs.cloudflare.com/ajax/libs/bignumber.js/8.0.2/bignumber.min.js" integrity="sha512-7UzDjRNKHpQnkh1Wf1l6i/OPINS9P2DDzTwQNX79JxfbInCXGpgI1RPb3ZD+uTP3O5X7Ke4e0+cxt2TxV7n0qQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
Sahand Zeynol
  • 156
  • 2
  • 9
  • What if the values returned are not string but numbers from an API. Is there no way we can avoid rounding up for numbers. – Kiran Dash Feb 06 '22 at 14:09
  • 1
    Don't deserialize the received data, so it would remain intact (as a string number) and no data will be lost. Then you can process the number as @SahandZeynol mentioned. – Hamed Motallebi Feb 08 '22 at 13:52