ERC20 Decimals – Understanding ERC20 Decimals in Smart Contracts

erc-20smart-contract-walletssoliditysolidity-0.8.x

How will I tell the EVM and wallet about the decimal?
Do they automatically read it from the constructor function???

Best Answer

As explained here, the decimals in an ERC20 token are just for representation to the user. The EVM has nothing to do with it. A wallet that recognizes ERC20 tokens and knows how many decimals a token has (by calling decimals() function), can represent the number of tokens to the user in a more readable way.

You know that Solidity does not support floating point numbers, so we use to represent a floating point number in a uint by dedicating some of the numbers to consider them as 'decimals'.

For example, if you have a custom token that you need to allow 2 decimals of precision, then you could represent the number 5.34 as 534 in Solidity and have a state variable or function decimals() that returns the value 2 to let us know that 534 has actually 2 decimal numbers which are the last ones and we could then show the user in the frontend 5.34.

Check the documentation of the OpenZeppelin ERC20 decimals() function: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol#L87