just wanted to check with you if my thinking is correct and this is the correct way of approaching percentage calculation:
We have the following constants:
userShares = 938186007644982137678069526
globalShare = 196444905942680952896579643162
percentage = percentage of userShare in relation to globalShares
threshold = 10%
If we divide userShares by globalShare we would get 0.004775822529695566. And if we want to display that in % terms the way we are used to in real world we need to multiply it by 100 so that it give us 0,475%. So the % is very small in the beginning but what I want to accomplish is something that accounts for small percentages like 0.47% in the beginning but then also accounts for 10% in the future.
I want to create a feature where I say:
if (percentage >= threshold) {do something}
So in order to calculate the percentage I did:
function getUserSharesPercentage() external view returns (uint256 percentage) {
// Get the total user shares
uint256 totalUserShares = 938186007644982137678069526;
// Get the global shares
uint256 totalGlobalShares = 196444905942680952896579643162;
// avoid dividing by 0
if (totalGlobalShares == 0) {
return 0;
}
// Use a larger scaling factor first to prevent loss of precision
uint256 SCALE = 1e6;
// First multiply userShares by SCALE to prevent truncation
uint256 scaledShares = totalUserShares * SCALE;
// Then divide by totalGlobalShares
percentage = (scaledShares / totalGlobalShares) ;
return percentage;
}
- The result of this function gives me 4775. So now if I want to compare the result of
getUserSharesPercentage
that is 4775 to 10%, I need to correctly also represent the 10% in relation to 4775.
If we want to represent % in solidity we use Basis points: 1% is represented by 1_00. 13% is represented by 13_00 and 100% is represented by 100_00. So following this logic I should compare 4775 against ((10_00) * 1e6), correct?
Or should it only be 10 * 1e6 = 10%
- Also if we used 1e4 as a scaling factor the result of the function would be 47, so 2 decimal places less so that means we would need to also use ((10_00) * 1e4), correct?
Thank you very much for your help and time reading my case!
Best,