1
contract test {
    function calculatePrice(uint a, uint b) public pure  returns (uint) {
        return (a * (b / 100));
    }

    function calculatePrice2() public pure  returns (uint) {
        return (80 * (60 / 100));
    }
}

So, the above two functions even though completely same give different answers. for the first function if you pass a=80 and b=60 answer is zero but if you call the second function the answer is 48.

Why? the code is exactly the same except the first function is dynamic

Sam
  • 55
  • 6

1 Answers1

3

The first function calculates with unsigned integers, meaning there are no decimals.

It first calculates 60 / 100, which results in 0 (integer, no decimals). And then calculates 80 * 0, which is still 0.


The second function takes the intermediate result as the fixed point number type.

It first calculates 60 / 100, resulting in 0.6 (fixed point number, not integer). And then calculates 80 * 0.6, resulting in 48.

Petr Hejda
  • 40,554
  • 8
  • 72
  • 100
  • `function calculatePrice3(uint a, uint b) public pure returns (uint) { return a * b / 100; }` will also return 48, so how does the omittance of brackets affect the answer? – Sam Oct 28 '22 at 09:49
  • @Sam When there's no parentheses present, it calculates from left to right (but still giving precedence to `*` and `/` over `+` and `-`). So in this case, the function first calculates 80 * 60, which is 4800. And then divides by 100, resulting in 48. – Petr Hejda Oct 30 '22 at 17:13