0

What is the best practice for doing this?

In the ERC20 standard having a public decimals: uint256 is marked as optional. But obviously you cannot display a token balance in the UI without having the decimals.

So how should I handle the case where the decimals field is not there? Should I just assume the contract implements 18 decimals?

What is the standard here? Is it safe to say that 95% of contracts implement the decimals variable?

3
  • 1
    Yes. And the remaining 5% (typically very old ones, before it became a standard to conform with the standard) are implementing either Decimals or DECIMALS. What is the address of the token which you are having this issue with? Oct 13 '20 at 17:40
  • It's general purpose. A user adds an address for an erc20 contract and I want to be able to infer what the decimals for that contract is. So it's safe to assume that the decimals variable will be there? I am happy to accept 5% redundancy. Oct 13 '20 at 17:41
  • 1
    So try decimals first. Then DECIMALS. Then Decimals. Then default to 18. If you need help with coding it using web3.js, then let know. Oct 13 '20 at 17:42
1

The concept of decimals is purely for user-friendliness - inside the blockchain there are no decimals. That's why it's optional.

If there are no decimals then you simply display what the token amount inside the contract shows - things get easier than with decimals. So it behaves like decimals was 0.

This concept is rather confusing for many people. You can read more for example here: https://ethereum.stackexchange.com/a/72481/31933

5
  • I understand what the decimals are for. What I want to do is know how to parse the uint256 on the UI if there are no decimals specified. If the decimals are 18 you can divide it by 10^18. If there are no decimals variable in the contract, then what is the best method for obtaining what the intended decimals are. e.g. the token list standard suggested by uniswap. Oct 13 '20 at 17:40
  • This user is clearly interested in decimals for offchain purpose and not for onchain purpose (quote: "obviously you cannot display a token balance in the UI without having the decimals"). Oct 13 '20 at 17:41
  • As I said, if there are no decimals you have to assume it's 0 - unless you explicitly see in the source code something else (which would be rather strange). So you display the same number you get from the contract Oct 13 '20 at 17:43
  • I would actually say default to 18 (because of how ETH is regarded everywhere). But I guess it's subjected to opinion. Oct 13 '20 at 17:44
  • Well you can of course display whatever you want, but I do think the "right" thing would be to display as 0 decimals. Oct 13 '20 at 17:51

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.