Solidity Percent Change – Calculating Percent Change in Solidity Contracts

remixsolidity

So I'm using Remix and have the following code:

pragma solidity ^0.4.11;

contract Negs {

  event Print(string _name, uint _value);

  function Test() {
    var startValue = 1000;
    var endValue = 800;
    Print ("Change1 - ", endValue / startValue);
    Print ("Change2 - ", 10*endValue / startValue);
    Print ("Change3 - ", 100*endValue / startValue);
    Print ("Change4 - ", 1000*endValue / startValue);
  }

}

And then looking at the events in the little box to the right once starting Test, I get the following values:

  • Change 1 – 0
  • Change 2 – 8
  • Change 3 – 14
  • Change 4 – 13

I know that Change 1 should be zero as there's no decimals, got that..but what about the other ones? Why wouldn't Change3 be 80 and change4 800?

Best Answer

In Solidity var is determining the type at first assignment and takes whatever fits. Read the warning here. Therefore your code translates into:

uint16 startValue = 1000;
uint16 endValue = 800;

Then, your calculation overflows as it translates into:

(100*800 % (2**16)) / 1000 = 14

and

(1000*800 % (2**16))/1000 = 13

Beware of var and assign it a type that you know will be fine at runtime! Also, use the SafeMath library whenever you need something decently secure+safe.

Related Topic