简体   繁体   English

使用 BigNumber 处理舍入问题

[英]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.如何使用 BigNumber 确保数字不四舍五入且计算准确。

 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>

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之后为了比较bigNumber 的值,最好使用“ compareTo ”参考文档

 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM