I have the following function to get the token balance from a web3 contract with web3.js The contract has 18 decimal point and interacting via Metamask:
async function getTokensBalance() {
const w3 = await new Web3(window.ethereum);
window.contract = await new w3.eth.Contract(myContr.abi, myContr.addr);
const balanceOf = await window.contract.methods.balanceOf(ethereum.selectedAddress).call();
console.log(balanceOf);
}
This returns the following string:
1399999999999999989100000000000006785
I want to now convert those to tokens number, but the rounding up creates an issue because it gives more token that it actually has.
My expected results are either this:
1399999999999999989.100000000000006785
or this worst case scenario this:
1399999999999999989
But instead I get this when trying to convert with either Number() or w3.utils.fromWei() this:
1400000000000000000
or
1.4e+36
Which obviously throws an error since the user does not have that much tokens.
I also tried to pass directly the string form of balanceOf but get the error:
Uncaught (in promise) Error: invalid BigNumber string How do I solve this?