I made a page where you can enter an amount of token and it gets swapped to another token.
It works until I use a number above 999. My smartcontract gets wei, so I have to transform the normal number to wei with the function below.
const toWei = amount => {
return amount * Math.pow(10, 18)
}
I get huge numbers out and I get this error
Error: invalid BigNumber string (argument="value", value="2e+21", code=INVALID_ARGUMENT, version=bignumber/5.6.0)
What can I do that this does not appear and is best practice?
Best Answer
The string
"2e+21"
is not valid for theBigNumber
class.JavaScript uses IEEE 754 numbers, which means any value above around
0.009
would suffer precision loss, and Ethereum is quite picky about numbers not being approximate.You should use strings for large values, or use the convenience functions provided for converting units, such as
ethers.utils.parseEther("1.0")
which handles string values.Here is more info on why you need Big Number: https://docs.ethers.io/v5/api/utils/bignumber/#BigNumber--notes-safenumbers