I am trying to find a percentage using the Big Number library from @openzeppelin/test-helpers
Here is the code:
var someVarABC = new BN('2706');
var someVarDEF = new BN('5060584');
var total = someVarABC.add(someVarDEF);
var percentage = (someVarDef.div(total)).mul(new BN('100'));
The error I get is:
Error: Assertion failed
at assert (node_modules/web3-utils/node_modules/bn.js/lib/bn.js:6:21)
at BN.divmod (node_modules/web3-utils/node_modules/bn.js/lib/bn.js:2329:5)
at BN.div (node_modules/web3-utils/node_modules/bn.js/lib/bn.js:2425:17)
at Context.<anonymous> (test/ERC20/SomeToken.test.js:84:48)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (node:internal/process/task_queues:94:5)
I know the problem is the division part where the result is .99 before multiplying by 100 but how can I work around this? I think on the solidity side there wouldn’t be an issue because fractional numbers are usable during calculations but just not to store in variables which is something I can work with but how do I fix the truffle test?
try this
var percentage = someVarDef.mul(100);
percentage = percentage.div(total);
If you need to use BN then do it, but so far I haven't had to use the BN library as my numbers aren't "that" big.
I had to use BN because I was getting “invalid array length” error. When I switch the 100 to a BN I got the same error in my original post. Here is the new code I tried:
var percentage = someVarDef.mul(new BN('100'));
percentage = percentage.div(total);
Error: Assertion failed
at assert (node_modules/web3-utils/node_modules/bn.js/lib/bn.js:6:21)
at BN.divmod (node_modules/web3-utils/node_modules/bn.js/lib/bn.js:2329:5)
at BN.div (node_modules/web3-utils/node_modules/bn.js/lib/bn.js:2425:17)
at Context.<anonymous> (test/ERC20/SomeToken.test.js:86:17)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (node:internal/process/task_queues:94:5)
1 Like
This might be a specific OZ question that needs to answer. @frangio Maybe you know more about this specific import? Thank you for the assistance.
1 Like
let abc = new BN('2706');
let def = new BN('5060584');
let total = abc.add(def);
let percentage = def.mul(new BN('100')).div(total);
This works. Note you can also do def.muln(100)
.
2 Likes
I apologize. It was my embarrassing error where I didn’t assign my total var the new value after using the add function.
total.add(someVarDef);
Instead of:
total = total.add(someVarDef);
Which resulted in me dividing by zero
Thank you for the help
1 Like
I would also like to note that “Error: Assertion failed” is a less-than-helpful error message.
Got XXX, expected YYY would be helpful.
1 Like