12

In React, I use a Web3js call function to get a value. The returned value is in Wei. However, I want to render it in Ethers. What would be the best way to do it?

12

In web3.js 1.0, use this:

web3.utils.fromWei(number [, unit])

doc

15

I think you're looking for fromWei. In web3.js 0.2x.x:

web3.fromWei(n, 'ether')
23
  • Thanks for the answer. For some reason, I'm getting "Cannot read property 'fromWei' of null" – Ruham Mar 5 '18 at 6:04
  • Is web3 null? – user19510 Mar 5 '18 at 6:05
  • No, the function returning Wei works. I imported Web3 from 'web3', and set a current provider. – Ruham Mar 5 '18 at 6:09
  • let web3 = new Web3(Web3.currentProvider) after which {web3.fromWei(price, 'ether')} – Ruham Mar 5 '18 at 6:10
  • And now, the error is: new BigNumber() not a number: [object Object] – Ruham Mar 5 '18 at 6:10
3

web3.utils.fromWei(yourValue, 'ether')

^^^ You must use the utils library. If you're getting the weird, TypeError: web3.fromWei is not a function and you're trying to console log the output, try setting the function call to a constant and then console logging that constant. Like so...

yourValue = returned amount of ether

returnValue = web3.utils.fromWei(yourValue, 'ether')

console.log(returnValue)

0

You have

web3.utils.fromWei('1', 'ether');

This results in the following: 0.000000000000000001

This assumes that your parameter is 1 wei and you want to convert it to ether.

You can also do it the other way around

web3.utils.toWei('1', 'ether');

This results in the following: 1000000000000000000

This assumes that your parameter is 1 ether and you want to convert it to wei

In both cases the second parameter is optional and defaults to "ether".

You can use all available ETH units as second parameter (e.g. gwei, shannon, szabo, etc.).

For more information you can check the official documentation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.