There doesn't seem any obligation in the ERC20 standard to provide the number of decimals anywhere, yet etherscan and all other services can automatically determine the number of decimals of a token. How is that done?

Is there an automated way (through RPC to geth) to get the number of decimals of a token defined by some contract?


For an ERC20 token, number of decimals are defined in the contract deployed on the address of that token.


pragma solidity ^0.4.11;
import 'zeppelin/contracts/math/SafeMath.sol';
import 'zeppelin/contracts/token/ERC20.sol';
contract ExampleCoin is ERC20 {
  using SafeMath for uint256;
  string public symbol = "EXAMPLE";
  string public name = "ExampleCoin";
  uint8 public decimals = 18;
  mapping (address => uint256) balances;
  mapping (address => mapping (address => uint256)) allowed;
  function ExampleCoin() public {
    balances[msg.sender] = 1000 * (10 ** uint256(decimals));
    totalSupply = 1000 * (10 ** uint256(decimals));

Every ERC20 contract follows same set of standards. All of them have a public decimal value (Thank you open Zeppelin)

All you need is to read that decimal value from the contract's address.

What is even more exciting, you can use generic ABI to connect to any ERC20 contract address and fetch its decimal value. See here

I hope this helps!

| improve this answer | |
  • What confuses me here is that we're assuming that there's a member variable called "decimals" that has the number of decimals... but this is not in the ERC20 standard! How safe is it to make this assumption? – The Quantum Physicist Jul 4 '18 at 19:58
  • please have a read on ERC20 standards its there along with name and ticker: theethereum.wiki/w/index.php/ERC20_Token_Standard – blockwala Jul 4 '18 at 20:00
  • As you see there "Some of the tokens include further information describing the token contract", not all tokens implement "decimals" member variable. It seems not to be obligatory. But then what you're saying is that I have to assume that this value is there. – The Quantum Physicist Jul 4 '18 at 20:09
  • Yes, I haven't come across a erc20 token that does not use it because it is quite necessary to conduct an ICO exchange for ethereum . Even in ethereum 10 ^ 18 Wei = 1 Ether. You can always keep a simple check and show the user if it doesn't exist for the contract but then again I will emphasise on the fact that is not the usual standard ice are conducted on. – blockwala Jul 4 '18 at 20:12
  • Last question, if you don't mind. Is it possible to use RPC with the generic ABI like you mentioned? Because from what I see, it uses web3 interface in the link you provided, and I only use json rpc. – The Quantum Physicist Jul 4 '18 at 20:16

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.