3

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.

1
  • If working in a console, I often just send a number as a string: for example function("123") (where 123 is actually a big number) Instead of using .toString() I just add " " around the number
    – Sky
    Commented Mar 17, 2022 at 10:40

2 Answers 2

2

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:

a.lt(b)
a.lte(b)

as an example

0

Try converting both the big number ('balance_before") and the other number you are comparing with toString(). So compare string to string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.