Solidity – How to Calculate the Number of Ether or Any Token with Known Decimals

solidity

How do I convert 2060881467756432366 into Ether which has 18 decimals.

More specifically I need to be able to do this for multiple tokens and I know how many they have plus how many decimal points the token has.

Best Answer

To convert from a Big Number -> Float can be done manually like so:

places = 18
integer = 10**places
number = 2060881467756432366 
decimal = number / integer
print(decimal)

or by using web3

w3.fromWei(2060881467756432366 , "ether")

the same works inversely with toWei()

To get the number of decimals can be obtained from the contracts decimals function in that contract.

if you do not have the abi this is standard in ERC20 contracts so you can use any ERC20 ABI.

decimals is NOT required for an ERC20 token but it is recommended and will most likely exist.

contract = w3.eth.contract(address=contract, abi=abi)
contract.functions.decimals().call()
>>> 18
Related Topic