I have total token 99,999,999.99999457, It is 8 decimal, but when I do like below I get 99999999, I expected 99,999,999.99999457:

  const decimals = await this.contract.methods.decimals().call();
  const decimalsBN = this.web3.utils.toBN(decimals);
  const divisor = this.web3.utils.toBN(10).pow(decimalsBN);
  const balanceWei = await this.contract.methods.balanceOf(address).call();
  const balanceWeiBN = this.web3.utils.toBN(balanceWei);
  return balanceWeiBN.div(divisor).toString();

From the official documentation of BN:

Note: decimals are not supported in this library.

Here, the term decimals refers to numeric values with digits after the decimal point (i.e., non-integers).

So in short, you'll need to npm install bignumber.js, and then in your script, the easiest way IMO:

const BigNumber = require("bignumber.js");
const balance = await this.contract.methods.balanceOf(address).call();
const decimals = await this.contract.methods.decimals().call();
const bn = new BigNumber(balance + "e-" + decimals);
return bn.toString();
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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