web3.js – How to Use toWei() Function for Tokens with 2 Decimals

tokensweb3js

I am trying to convert amount in wei using web3js function called toWei().

Here is my code:

 var etherwithdrawamount1=web3Infura.utils.toWei(etherwithdrawamount, 'wei'); 

Now, the problem is that the token amount is not calculating correct, because the token has 2 decimals.

In web3 documentation: https://web3js.readthedocs.io/en/1.0/web3-utils.html#towei there is no places for 2 decimals.

number – String|Number|BN: The value.

unit – String (optional, defaults to "ether"): The ether to convert from.

Possible units are :

noether: ‘0’
wei: ‘1’
kwei: ‘1000’
Kwei: ‘1000’
babbage: ‘1000’
femtoether: ‘1000’
mwei: ‘1000000’
Mwei: ‘1000000’
lovelace: ‘1000000’
picoether: ‘1000000’
gwei: ‘1000000000’
Gwei: ‘1000000000’
shannon:‘1000000000’
nanoether: ‘1000000000’
nano: ‘1000000000’
szabo: ‘1000000000000’
microether: ‘1000000000000’
micro: ‘1000000000000’
finney: ‘1000000000000000’
milliether: ‘1000000000000000’
milli: ‘1000000000000000’
ether: ‘1000000000000000000’

So, how to get the correct value in toWei() where the token decimals are 2?

Best Answer

Try this:

function strtodec(amount,dec){
stringf = "";
for(var i=0;i<dec;i++){
stringf = stringf+"0";
}
return amount+stringf;
}

You need to call this function using this method:

strtodec(amount,'your token decimal here')

The logic is this: The function adds zeros in the amount as many as decimals you want.