1

To calculate with x == .5 y == .6 (n)x / (n)y = z and the store the result z in uint (precision n == 1000) ... how would I go about that in solidity?

I've read this How to do Solidity percentage calculation? ... but it is not directly helpful to me in dividing two percentages, because

(100)x * (100)y /100 === does not come close to the float result (.8333).

I'm totally lost here.

The units x or y are not ether in my case

2

The trick is to work out a scheme that works exclusively with integers.

pragma solidity 0.5.0;

contract Div {

    function divider(uint numerator, uint denominator, uint precision) public pure returns(uint) {
        return numerator*(uint(10)**uint(precision))/denominator;
    }
}

You can send it 5,6,4 to indicate that you want 4 significant digits back (without the decimal). On the client side, you can divide the result by 10**4 to convert the response (8333) to a decimal.

Note that the client itself specified the degree of precision needed so it's fair to assume that the client also knows how to interpret the response. Think in pennies instead of dollars, for example.

enter image description here

It's worth noting that there is no rounding up, only truncation. The solution to that issue is to add an extra decimal of precision, add 5 and then remove a decimal of precision.

pragma solidity 0.5.0;

contract Div {

    function divider(uint numerator, uint denominator, uint precision) public pure returns(uint) {
        return (numerator*(uint(10)**uint(precision+1))/denominator + 5)/uint(10);
    }
}

2,3,4 yields 6667 which is correct rounding.

Hope it helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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