0

How do I get testDivCast() to return the same result as testDivLiteral()?

pragma solidity ^0.5.1;

  function testDivLiteral() external pure returns (uint16) {
    return (1 / 5) * 100;
  }
  // Expected: 20 | Result: 20

  function testDivCast() external pure returns (uint16) {
    return (uint16(1) / uint16(5)) * uint16(100);
  }
  // Expected: 20 | Result: 0
  • 1
    Just postpone division as much as possible (without changing the arithmetic expression of course). – goodvibration Sep 3 at 17:17
1

In this case, the simplest solution would just be to re-order the terms in the equation.

ie,

return (uint16(1) * uint16(100)) / uint16(5);

If you multiply first and then divide, then you won't lose as much accuracy due to rounding. In general this tends to do the trick, but be aware of overflows if you'll be working with values close to the limit of your integer type.

  • Thank you! Any idea why this is the case? Does division change the type of the uint16s? – Anthony Lusardi Sep 3 at 17:28
  • 1
    Literals have some magic powers that integer types don't (solidity.readthedocs.io/en/v0.5.11/…). Since integers can't handle decimals, the value of the integer is evaluated after each step. So, 1/5 = 0.2, which gets rounded down to 0. Then 0 * 20 is still 0. – AnAllergyToAnalogy Sep 3 at 17:39

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.