2

I would like to do a division in my solidity smart contract but the result is always 0, I found some stuff on stackoverflow about this problem, this is working with this function but not with SafeMath, someone know why?

    uint amount1 = 100;
    uint amount2 = 142;

    result = SafeMath.div(amount1, amount2); // return 0

Regards

0

1 Answer 1

3

I found the solution right after I submitted this question.

100/142 = 0.7042 which is a decimal less than 1. Because solidity only works with integer, I'm getting only the initial 0.

To get the right result, I did: 100 * 10000 / 142 = 7042 which is exactly what I wanted!

5
  • 1
    0.7042 is "decimal < 0" it is "decimal < 1"!!! May 8, 2018 at 4:53
  • And BTW, SafeMath.div is a waste of time, just use / (Zeppelin too, will realize it at some point and get rid of it). May 8, 2018 at 4:55
  • But what about the overflow and security?
    – oktapodia
    May 8, 2018 at 9:29
  • There cannot be any overflow in division, and the only "security" issue here is division by 0, which will trigger an exception in either case (whether you use div or /). May 8, 2018 at 9:36
  • Oh yes you are right but I prefer to still use it to keep a consistent code
    – oktapodia
    May 10, 2018 at 0:31

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.