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?
5 Answers
I think you're looking for fromWei. In web3.js 0.2x.x:
web3.fromWei(n, 'ether')
- 27,999
- 2
- 30
- 48
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)
- 693
- 2
- 10
- 17
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
- 173
- 9
Fetch Balance in eth complete syntax.
{
var web3 = new Web3(window.ethereum);
await window.ethereum.send("eth_requestAccounts");
var accounts = await web3.eth.getAccounts();
var account = accounts[0];
var balance = await web3.eth.getBalance(account);
var amount = await web3.utils.fromWei(balance);
console.log(amount);
}
- 1
- 1
web3null? – user19510 Mar 05 '18 at 06:05nullissue? Or has that been resolved? – user19510 Mar 05 '18 at 06:16nyou're passing? Sounds like it's some sort of object. – user19510 Mar 05 '18 at 06:22fromWei? What? – user19510 Mar 05 '18 at 06:25web3.fromWeidoes what you want:web3.fromWei(1e18, "ether"). Then figure out what the actual value you want to pass in is. – user19510 Mar 05 '18 at 06:25web3? (Try doingconsole.log(price);.) – user19510 Mar 05 '18 at 06:28console.log(price)passed to fromWei returns 0 :/ – Ruham Mar 05 '18 at 06:32new BigNumber() not a number: [object Object]? Now you're saying it produces no error but returns 0? – user19510 Mar 05 '18 at 06:33web3.fromWeiworks if you pass in the correct value, and the rest is just debugging for you to do. – user19510 Mar 05 '18 at 06:34web3.fromWei(console.log(price), ...)? Don't do that. Just doconsole.log(price)to see what its value is. – user19510 Mar 05 '18 at 06:35web3.fromWeitoweb3.utils.fromWei;) – GIA Apr 29 '21 at 18:39