Numbers in Etherum and Javascript

So I feel like I made some significant progress today after going through this piece on numbers in Ethereum and Javascript. It’s quite a bit of trouble, especially because of the way that numbers and storage is returned from web3 call() and getStorageAt() functions.

Case in point, I’m trying to compute the sum of a Ethereum amount multiplied by a percentage. Both values are stored in wei, which has eighteen decimal points. If one simply multiplies the two together, you get a rate that is actually off by another 10^18, so the result of the division needs to be divided by this factor before it is returned.

The web3 library in Javascript relies on BN.js, which stands for big number. It doesn’t work on decimals, they have to be passed as strings. So I can’t just pass 10**18 to make a big number, I have to return it as a string.

let BN = web3.utils.BN;
let decimal = new BN((10**18).toString())
let balance = new BN("196144358288748402370");
let rate = new BN("2500000000000000");
let result = balance.mul(rate).div(decimal);
console.log("Result: " + web3.utils.fromWei(result));
> Result: 0.490360895721871005

Performing this percentage calculation in Vyper is simple arithmetic, where all the numbers are uint256.

res: uint256 = (balance * pct) / 10 ** 18