1

how can i calculate: 1083.83 / 8.25 = 131.37.

As I see its not possible in simple way. I have tried a lot of math function but not works.

Is there any solution for this?

6
  • 1
    Maintain each one of them as a pair of numerator and denominator. If the same denominator is used everywhere (for example, 100 in your case), then you only need to maintain the numerators (for example, 108383, 825 and 13137 in your case). When you apply arithmetic operations, always try to "postpone" the operation / (or div if you're using some sort of SafeMath library) as far as possible towards the end of the computation, in order to minimize precision-loss. Oct 5, 2020 at 12:51
  • For example, instead of xN / xD + yN / yD, you can do (xN * yD + yN * xD) / (xD * yD). Oct 5, 2020 at 12:58
  • And instead of xN.div(xD).add(yN.div(yD)), you can do xN.mul(yD).add(yN.mul(xD)).div(xD.mul(yD)). Oct 5, 2020 at 12:58
  • Does it answer your question? Or do you have a specific scenario in which you need a different solution? If yes, then please add it to your question. Oct 5, 2020 at 13:43
  • This answer resolved my issue but i can't found button "Resolved".
    – progy85
    Oct 5, 2020 at 13:54

1 Answer 1

2

Maintain every non-integer entity in your code as a pair of numerator and denominator.

If the same denominator is used everywhere (for example, 100 in your case), then you can maintain only the numerators (for example, 108383, 825 and 13137 in your case).

Whenever you apply an arithmetic computation, try to "postpone" the operation / (or div if you're using some sort of SafeMath library) as far as possible towards the end of the computation, in order to minimize precision-loss.

For example, instead of:

uint256 a = xN  /  xD   +  yN  /  yD  ;
uint256 b = xN.div(xD).add(yN.div(yD));

You can do:

uint256 a = (xN  *  yD   +  yN  *  xD )  / (xD  *  yD );
uint256 b =  xN.mul(yD).add(yN.mul(xD)).div(xD.mul(yD));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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