Incorrect Product of BigDecimals

My solidity function emits an event with a uint256 of: 5060584000000000000000000

The problem is on the truffle side in my javascript test. Here is the code:

const { BN, expectEvent, constants } = require('@openzeppelin/test-helpers');
const amount = new BN('100);
const price = new BN('5060584000');
const decimalsA = new BN ('5');
const decimalsB = new BN ('18');
const baseTen = new BN('10');
var totalValue = amount * price;
totalValue = totalValue * (baseTen ** (decimalsB - decimalsA));

The totalValue var always incorrectly returns 5060584000000000291504128 in the javascript test but the event correctly gives me 5060584000000000000000000.

This causes my test to fail of course. What am I doing wrong? (assuming something with big number precision?)

Seems that the fix for this is similar to this post: ERC20 decimals, specifying a big number - #4 by abcoathup

where I needed to use big number libraries multiply and power functions to do the calculation as the number is too big for JavaScript. The test is now working with:

const { BN, expectEvent, constants } = require('@openzeppelin/test-helpers');
const amount = new BN('100);
const price = new BN('5060584000');
const decimalsA = new BN ('5');
const decimalsB = new BN ('18');
const baseTen = new BN('10');
var totalValue = amount.mul(price);
totalValue = totalValue.mul(baseTen.pow(decimalsB.sub(decimalsA);
2 Likes