'Assigning a 'Value' Parameter to an Ethereum Transaction

I am trying to assign a value of 0.05 Ether to the value parameter for an Ethereum transaction as described in the code below. I do not understand how to convert 50000000000000000 Wei (0.05 Eth) to the format described '0x29a2241af62c0000'. Please could someone advise me on how to convert 50000000000000000 wei to this format and what is it exactly?

//Sending Ethereum to an address
sendEthButton.addEventListener('click', () => {
  ethereum
    .request({
      method: 'eth_sendTransaction',
      params: [
        {
          from: accounts[0],
          to: '0x2f318C334780961FB129D2a6c30D0763d9a5C970',
          value: '0x29a2241af62c0000',
          gasPrice: '0x09184e72a000',
          gas: '0x2710',
        },
      ],
    })
    .then((txHash) => console.log(txHash))
    .catch((error) => console.error);
});


Solution 1:[1]

0x29a2241af62c000 is the hexadecimal expression of the decimal number 187500000000000000.

You can use the native JS method toString() to convert a decimal number to its hexadecimal form.

'0x' + (50000000000000000).toString(16)

returns

0xb1a2bc2ec50000

Or if you want to use web3, there's the numberToHex() method.

Solution 2:[2]

"0x" + Number(Web3.utils.toWei("0.05", "ether")).toString(16)

I think this is the more accurate way to achieve, and it works for me, first convert your value to wei then to hex

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Petr Hejda
Solution 2 arslan