I am creating a contract that issues tokens. I would like an account that holds tokens to be able to check what percentage they own out of all the tokens issued. I know that Ethereum has not implemented floating point numbers yet. What should I do?
It's probably best (lowest gas cost and trivial to implement) to perform that calculation on the client rather than in Solidity.
If you find you need it in Solidity, then it's just a matter of working with integers by shifting the decimal point. Similar to: https://en.wikipedia.org/wiki/Parts-per_notation
For example, this function let's you decide the degree of precision and uses one extra degree of precision to correctly round up:
pragma solidity ^0.4.6;
contract Divide {
function percent(uint numerator, uint denominator, uint precision) public
constant returns(uint quotient) {
// caution, check safe-to-multiply here
uint _numerator = numerator * 10 ** (precision+1);
// with rounding of last digit
uint _quotient = ((_numerator / denominator) + 5) / 10;
return ( _quotient);
}
}
If you feed it 101,450, 3 you get 224, i.e. 22.4%.
Hope it helps.
You could use binary point
or fixed number representation
. Introduction to Fixed Point Number Representation For example
11010.1 in base2 = 1 * 24 + 1 * 23 + 0 * 22 + 1 * 21 + 0* 20 + 1 * 2-1 = 26.5
Percentage is calculated by
// x is the percentage
a/b = x/100 => x= (100*a)/b
to calculate the division of big numbers, you can use FixidityLib.sol library.
function divide(Fixidity storage fixidity, int256 a, int256 b) public view returns (int256) {
if(b == fixidity.fixed_1) return a;
assert(b != 0);
return multiply(fixidity, a, reciprocal(fixidity, b));
}
There are too many mathematical libraries or contracts and each implements divide operation differently:
DSMath Contract
© 2022 - 2024 — McMap. All rights reserved.