Sorry for the newbie question. There are a lot of solutions but non of them worked for me. I am getting an account's balance with
const balance_before = await ethers.provider.getBalance(redeemer.address);
The returned balance_before
is
BigNumber { _hex: '0x021e0bf99fe8b4390000', _isBigNumber: true }
I want to convert this to a normal number. When I try console.log(balance_before.toNumber())
I get the following error:
Error: overflow (fault="overflow", operation="toNumber", value="9998998184576000000000", code=NUMERIC_FAULT, version=bignumber/5.3.0)
I can use .toString()
this returns 9998998184576000000000
but in a string format and I need to compare this value with a number so it is not useful. How can I convert the balance_before
to a number?
PS: I am testing this with hardhat and chai.
Best Answer
You're getting an overflow error, because javascript can't represent this number with enough accuracy. Even if you were able to convert it to a number, comparing it with any other would not be reliable, because of the imprecision.
That is actually exactly what BigNumbers are for.. So instead of converting it and comparing it, use BigNumber's comparison operators: https://docs.ethers.io/v5/api/utils/bignumber/ You can use:
as an example