Last active
February 2, 2023 11:10
-
-
Save bartubozkurt/cdf134ae0286be9109a7f8c2fd7f0494 to your computer and use it in GitHub Desktop.
DivideBeforeMultiply.sol
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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