Web3.js ERC20 Decimals – Handling Decimals in ERC20 with Web3.js

web3js

I am using web3 v1.0.27 and trying to send erc20 tokens. These tokens have a decimal of 18 but might have a different decimal. Trying to keep it generic. I have tried the following.

  const amountToSendinDecimal = amountToSend * Math.pow(10, decimal);
  const amountToSendinDecimalBN = new BigNumber(amountToSendinDecimal);

With a decimal of 18 and value of 3178.44. I keep on getting the following error.

[BigNumber Error] Number primitive has more than 15 significant digits: 3.1784400000000003e+21

Cannot seems to find a work around for it.

Any suggestions.

Best Answer

When you have web3 js, you can do it with either of the following ways.

var amountToSend = 2;
var weiAmout = amountToSend * 1e18;
var weiAmount2 = web3.toWei(amountToSend);
Related Topic