Solidity Tokens – How to Calculate Percentage in Solidity Tokens

soliditytokens

I'm currently learning how to write smart contracts.
While studying some code, I came across this line: ‭

uint256 a = value.ceil(basePercent);

(with: uint256 public basePercent = 100;)

Then one calculates 1% of the value with:

 uint256 onePercent = a.mul(basePercent).div(10000);

But why was the first line of code necessary or what is it doing?

Best Answer

You can check with the code below that this line:

uint256 roundValue = SafeMath.ceil(_value, basePercent);

If your value _value is higher than basePercent, roundValue will be the number rounded on the hundred, otherwise the _value will be basePercent always.

Example: input = 1--> roundValue = 100

Example: input = 4111--> roundValue = 4200


Code:

Supposing a SafeMath library like the following:

pragma solidity ^0.5.0;

library SafeMath {
    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }
        uint256 c = a * b;
    assert(c / a == b);
    return c;
    }

    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        uint256 c = a / b;
        return c;
    }

    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        assert(b <= a);
        return a - b;
    }

    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        uint256 c = a + b;
        assert(c >= a);
        return c;
    }

    function ceil(uint256 a, uint256 m) internal pure returns (uint256) {
        uint256 c = add(a,m);
        uint256 d = sub(c,1);
        return mul(div(d,m),m);
    }
}

And the onePercent function:

import "./SafeMath.sol";

contract Percentage{
    
    uint256 public basePercent = 100;

    function onePercent(uint256 _value) public view returns (uint256)  {
        uint256 roundValue = SafeMath.ceil(_value, basePercent);
        uint256 onePercent = SafeMath.div(SafeMath.mul(roundValue, basePercent), 10000);
        return onePercent;
    }
}
Related Topic