Skip to content

Instantly share code, notes, and snippets.

@bartubozkurt
Last active February 2, 2023 11:10
Show Gist options
  • Save bartubozkurt/cdf134ae0286be9109a7f8c2fd7f0494 to your computer and use it in GitHub Desktop.
Save bartubozkurt/cdf134ae0286be9109a7f8c2fd7f0494 to your computer and use it in GitHub Desktop.
DivideBeforeMultiply.sol
/* Bad */
int totalValue = 275000;
int percentage = 2;
for (uint i = 0; i < 30; i++) {
totalValue += totalValue * percentage / 100;
}
/*
Exact value: 498124.436
Result: 498108
*/
/* Better */
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;
/*
Exact value: 498124.436
Result: 498124
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment