# Percentage calculation

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? Commented Jun 17, 2019 at 10:03
• sorry forgot to change. I'll edit it Commented 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... Commented Jun 17, 2019 at 11:22
• this function has just 1 input (value) and returns onePercent (of the value). Commented Jun 17, 2019 at 13:09

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 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? Commented Jun 18, 2019 at 7:22
• That's what I suppose. Commented Jun 18, 2019 at 7:36