5

Example value: 0x2c1c986f1c48000

from: here

Expected value back: 0.19866144 Eth

Malone
  • 1,590
  • 12
  • 23
Sunny
  • 295
  • 3
  • 8

3 Answers3

2

Try this with ethers.js utils:

ethers.utils.formatEther('1000000000000000000') // return 1.0
Kyeson
  • 121
  • 4
1

Ether fixed point numbers are higher precision than javascript floats, so you will need to use a library that supports those bigger values.

In Web3 you can simply do:

let bigNumber = web3.toBigNumber('0xFFFFFF')
web3.fromWei(bigNumber)
OneChillDude
  • 342
  • 1
  • 12
1

You can use the BigNumber library:

var value_wei = "0x2c1c986f1c48000";
var value_ether = new BigNumber(value_wei).dividedBy(new BigNumber("1000000000000000000");

To explain: Ethereum works with units of wei. 1 ether is 1e18 wei, so you have to deal numbers that are too large to be handled by javascript. The BigNumber library accepts representation of numbers a strings, so you can go around this problem.

Note that all functions in web3.js always return values in wei as a BigNumber object, so the return of web3.eth.getBalance(...) can be directly used with the lines above, for example.

Achala Dissanayake
  • 5,819
  • 15
  • 28
  • 38
gisdev_p
  • 1,801
  • 1
  • 9
  • 18