6

I've looked into the following answers, but have not found what I am looking for.

Any help is appreciated.

2
  • 2
    You need to use fixed-point arithmetic. Have you seen this example of solidity code that calculate percentage with given precision?
    – NewTwoEth
    Commented Jun 27, 2017 at 1:02
  • @blockchaindotsol What are you looking for that is not solved in the links you have pointed to?
    – Ismael
    Commented Jun 27, 2017 at 5:14

1 Answer 1

14

As seen in SO copying and pasting shamelessly to keep the users here.

It's probably best (lowest gas cost and trivial to implement) to perform that calculation on the client rather than in Solidity.

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%.

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