Handling Decimals in Complex Math within Solidity Contracts

contract-debuggingcontract-designcontract-developmentsolidity

I'm a bit lost on what to do with the following calculation. The problem is that decimals are being round up/down, which obviously doesn't give me the result I desire.

int totalValue = 275000;
int percentage = 2;

for (uint i = 0; i < 30; i++) {
  totalValue += totalValue * percentage / 100;
}

With the above code, the result is:

498108

The expected result is:

498124.436

I know that normally you could simply use the following calculation to work with a predetermined amount of decimals like so:

value * 10**4 (4 decimals)

But I haven't gotten that to work in this case, often resulting in insanely high numbers due to the multiplication and division that "do not make sense" once I revert the above calculation using:

value / 10**4

Thank you very much for your time. Any help would be very much appreciated!

Best Answer

You need to multiply before calculations and divide after that:

int decimals = 4;
int totalValue = 275000;
int percentage = 2;

totalValue = totalValue * 10**decimals;
for (uint i = 0; i < 30; i++) {
  int AddValue = totalValue * percentage;
  AddValue = AddValue / 100;
  totalValue += AddValue;
}
totalValue = totalValue / 10**decimals;

EDIT: fixed line 5 and the percentage calculation EDIT2: Actually you don't need to multiply the percentage and will get better results - fixed

Related Topic