Kiran Dash
Kiran Dash

Reputation: 4956

Handling rounding issue with BigNumber

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>

Upvotes: 1

Views: 931

Answers (1)

Sahand Zeynol
Sahand Zeynol

Reputation: 331

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>

Upvotes: 5

Related Questions