5

This question already has an answer here:

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

Any help is appreciated.

marked as duplicate by niksmac, Nicolas Massart, Richard Horrocks, Samuel Hawksby-Robinson, Rob Hitchens - B9lab Jun 27 '17 at 14:47

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

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

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.