# Is there a good way to calculate a ratio in Solidity (since there is no float/double)? [duplicate]

Any help is appreciated.

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