2

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();

2 Answers 2

3

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();
0

This code works with web3 without adding any additional libraries for any value of decimals:

const balance = await contract.methods.balanceOf(address).call();
const decimals = await contract.methods.decimals().call();
const unit = Object.keys(web3.utils.unitMap).find(key => web3.utils.unitMap[key] === web3.utils.toBN(10).pow(web3.utils.toBN(decimals)).toString());
console.log( web3.utils.fromWei(balance, unit) );

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.