Solidity ERC-20 – Converting Decimal Values to Unsigned Integers

erc-20solidity

In our platform, we reward users with ERC20 tokens based on the fixed formula.

number of articles user wrote * 0.01828 = number of tokens to be rewarded

So let's say a user wrote 5 articles (5 * 0.01828), they get 0.3656 tokens.

How do I convert that to uint256 so EVM can accept it?

p.s. I set my decimals places to 18.

Best Answer

Since you are dealing with token amounts it is possible to use fixed point arithmetic using the 18 decimals.

For example

function numTokens(uint articles) public pure returns (uint) {
    // Solc accepts numbers with decimals at compile time
    uint coef = 0.01828 * 10**18;
    // coef is 18280000000000000 and can be stored as an uint

    return articles * coef;
}
Related Topic