2

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?

2 Answers 2

0

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.

3
  • 1
    what is token decimal amount or string? Nov 27, 2018 at 12:14
  • You need to use the amount (integer) for whatever decimals you want :) Nov 27, 2018 at 12:15
  • Good approach! But it doesn't work for doubles in JS for example 0.1. Do you know any solution? @Yogesh-EtherAuthority.io
    – Yaya
    Sep 13, 2022 at 18:14
0

This variant can work with float:

function strtodec(amount, dec){
    var i = 0;
    if (amount.toString().indexOf('.') != -1) {
        i = amount.toString().length - (amount.toString().indexOf('.') + 1);
    }
    stringf = amount.toString().split('.').join('');
    if (dec<i){
        console.warn("strtodec: amount was truncated")
        stringf = stringf.substring(0,stringf.length - (i-dec));
    } else {
        stringf = stringf + "0".repeat(dec-i);
    }
    return stringf;
}

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.