[Ethereum] while converting number 0.001 to BN.js instance, error: Value must be an integer, hex string, BN or BigNumber instance

bignumberetherethereumjsweb3js

I want to transfer 0.001 token and I cannot use web3.utils.toWei(0.001) as the smart contract has 12 decimal instead of 18 decimal. How can I correct it ?

  var decimals = 12;
  var amount = web3.utils.toBN(web3.utils.toHex(0.001)); <--- Getting error here
  let value = amount.mul(web3.utils.toBN(10).pow(decimals));

The error is:

[number-to-bn] while converting number 0.001 to BN.js instance, error: invalid number value. Value must be an integer, hex string, BN or BigNumber instance. Note, decimals are not supported. Given value: "0.001"

Best Answer

BN will not accept decimal point numbers. You can do as follows:

var decimals = 12;
var value = (0.001*(10**decimals)).toString();
var amount = web3.utils.toBN(value);

Hope this helps