[Ethereum] Web3 js 1.0 is throwing big number error while transfering tokens

erc-20ethereumjsweb3js

When I tried to transfer more then 1000 tokens, it's throwing an error like as mentioned below (I'm using web3 js 1.0.0 34 beta version).

Error: [number-to-bn] while converting number 1e+23 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: "1e+23

Find code examples which I tried.

//var tokens = amount * 1e18;
//var tokens = amount * (10 ** 18);
//var tokens = parseInt(amount) * 1e18;
//var tokens = web3.utils.toBN(amount);
//var tokens = amount * Math.pow(10, decimal)
var tokens = web3.utils.toBN(amount * 1e18) ;

Does anyone faced this issue?

Best Answer

If you are using Web3.js and your token is using the standard 1018 decimal, then you can also use web3.utils.toWei() and web3.utils.fromWei() to get to and from the big numbers you want pretty easy.

In this situation you can try this:

var amount = 1000
var tokens = web3.utils.toWei(amount.toString(), 'ether')

"1000000000000000000000"

You can then easily convert that to a BN:

var bntokens = web3.utils.toBN(tokens)
Related Topic