Division/percentages is a required part of many applications but is difficult to implement since fixed
and ufixed
are not supported yet in Solidity. I've come up with this workaround:
pragma solidity ^0.4.9;
contract Math {
function Math() public {}
function percent(uint a, uint b) public constant returns(uint, uint) {
uint c = a*b;
uint integer = c/100;
uint fractional = c%100;
return (integer, fractional);
}
}
If I want to get 12% of 27 and call percent(27, 12)
, I correctly get back 3
and 24
representing 3.24
. The limitation to this of course is that percent(12.5, 100)
isn't possible.
However if I call percent(17, 359)
, I get back 61
and 3
. The real result is 61.03
, however, because fractional
is a uint
, the 0 in front of the 3 is dropped. Is there a way to find out if a fractional has a leading zero?
X * Y
and100
. Don't divideX * Y
by100
until you get to the point where you really need it. For example, suppose that later in your code you need to multiply this value byZ
, then at this point you doX * Y * Z / 100
.100/3 = 0.03
, and100/24 = 0.24