Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BigNumber multiplying decimal values in ethers

I want to do math - 100000 * 1.004 by using BigNumber values. The biggest problem here is that 1.004 is a float and BigNumber does not accept it. I am using ethers.js library for it.

I tried to use parseUnits("1.004", 18). I am using 18 because basically I am operating on stable coins prices.

I get BigNumber { value: "1004000000000000000" } from it. To do the math I have to parse 100000 also so I do it in the same way - parseUnits("100000", 18). After that I just do parseUnits("1.004", 18).mul(parseUnits("100000", 18)) to multiply them and I get BigNumber { value: "100400000000000000000000000000000000000000" }.

When I use formatUnits() method to get a number back I get 100400000000000000000000.0 where correct value should be 100000 * 1.004 = 100400.

What is the correct way of doing calculations like that by using the ethers.js library?

like image 225
Mickey Avatar asked Oct 16 '25 05:10

Mickey


1 Answers

I finally decided to use bignumber.js library for that. ethers.js does not support float values with decimals when bignumber.js does it perfectly without any formatting.

like image 83
Mickey Avatar answered Oct 18 '25 20:10

Mickey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!