Standard integer division

Handling the division in the previous scenario is just the same as working with integer divisions, as Ethereum doesn’t adopt floating point numbers. The division would result in a floor of the calculation with the remainder discarded. For example, the division 17/3 equals 5, with the remainder of 2 discarded. To fix this, we create a new method that does the following:

function calcul(uint a, uint b, uint precision) public pure returns (uint) {
require(b != 0);
return a * (10 ** (precision)) / b;
}

Note that the double asterisk, **, is a Solidity operator representing the exponentiation operation. In our example, 10 is the base whereas precision is the exponent.

If we divide 17 by 3 using the calcul() function, and we call the function with a precision of 5 (the number of digits after the decimal point), it will output 566,666, which can be displayed to the player as 5.66666. In this way, we can produce a float using integer division, though it still requires that in the frontend you divide the result by the equivalent value of (10 ** (precision)) to display the floating-point number.

Therefore, in the share_pension() function, we substitute the quotient by performing the following:

 Tpension[active_players[i].Paddress] = calcul(Tpension[user], remainingPlayers, 18);
To avoid security flaws, you can perform a division operation using the SafeMath secure library, available at the OpenZepplin repository: https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset