I am using BigNumber
from etherjs and I am doing this very simple operation:
const cost = BigNumber.from(3)
.div(BigNumber.from(1000))
.mul(BigNumber.from(3));
console.log(cost.toString());
It outputs '0', but should be 0.09.
Why? What am I doing wrong?
As far as I can tell from the documentation, Ethers'
BigNumber
only handles big integers. Nothing in the documentation mentions fractional values or precision or scale, all of which you'd expect to see in a library handling fractional values. Separately, the documentation mentions it currently usesBN.js
in its implementation ofBigNumber
.BN.js
doesn't handle fractional values. From its documentation:That's not terribly clear (most of the examples are in decimal), they probably meant fractional values aren't supported.
A couple of options for you:
You could work in units that are a multiple of the precision you need. For instance, if you need two digits of precision to the right of the decimal point, you'd work with values that are multiplied by 100. Then divide by 100 to get the whole portion for output, and do a remainder operation on 100 to get the fractional portion for output (formatting with a leading
0
if needed).There are several libraries for big numbers that handle fractional values, such as
bignumber
andbig.js
.