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?

  • where is the variable a used?
    – Sanjay S B
    Jun 17, 2019 at 10:03
  • sorry forgot to change. I'll edit it
    – 2stefan
    Jun 17, 2019 at 10:14
  • I agree that the ceil line doesn't make any sense it the given context (and on a fixed-point infrastructure such as that of Solidity in general (unless this function took two inputs - numerator an denominator, or numerator and resolution)). Perhaps you wold care to share the source of this code... Jun 17, 2019 at 11:22
  • this function has just 1 input (value) and returns onePercent (of the value).
    – 2stefan
    Jun 17, 2019 at 13:09

1 Answer 1


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


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;
  • thanks! So the advantage of getting roundValue is that if the token has 0 decimals you get results approximating 1% of the initial value?
    – 2stefan
    Jun 18, 2019 at 7:22
  • That's what I suppose.
    – alberto
    Jun 18, 2019 at 7:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.