2

I am trying to divide BN with a constant and I can't find the right function. Basically I wanted to divide 132876 by 1.30, 132876/1.30 for BN operations. Here is a snippet of what I tried.

const gasAmount = new BN(132876) 
console.log(gasAmount.div(new BN('1.30')).toString()) // 160
console.log(gasAmount.div(new BN(1.30)).toString())   // 132876

// expected: 102212 
2

Web3.js lib is already supporting BigNumber so you don't have to add the library twice. Try this:

const gasAmount = web3.utils.toBN(132876);
console.log(gasAmount.divn(1.30).toString());
14
  • Have you tried this? It gives the exact same result that this user is complaining about. You've only changed div(new BN(1.30)) to divn(1.30), which are essentially identical. And the reason why it doesn't work, is that class BN simply does not support decimals. – goodvibration Dec 20 '20 at 7:38
  • BTW, what does "you don't have to add the library twice" mean? There is no evidence of something like that in the question. – goodvibration Dec 20 '20 at 7:43
  • @goodvibration new BN is by default not supported in browsers, so I guess he added that library, but he don't need it, because he have web3.js already. – Miroslav Nedelchev Dec 20 '20 at 7:44
  • And ofcourse I've tried it, the question is have you tried it :) result - ibb.co/1vS5zv9 – Miroslav Nedelchev Dec 20 '20 at 7:46
  • 1
    P.S.: I'd still recommend to avoid using decimals anywhere in the code (other than for printing, displaying user data, etc). In other words, use muln(130).divn(100) rather than divn(1.30). – goodvibration Dec 20 '20 at 8:25
1

Class BN does not support decimals, as stated in the official documentation:

Note: decimals are not supported in this library.

So change this:

gasAmount.div(new BN(1.30))

To this:

gasAmount.mul(new BN(130)).div(new BN(100))

Or even to this:

gasAmount.muln(130).divn(100)
1
  • Undeleted the answer, because it appears that class BN actually does support decimals in a certain way (at least as input). The other answer is correct, and even provides a more simple solution (as I've also mentioned in the comments to it). I still recommend to avoid using decimals anywhere in the code (other than for printing, displaying user data, etc), so I'm keeping this answer here as an optional solution. – goodvibration Dec 20 '20 at 10:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.