How to calculate percentages in Solidity
A guide on calculating percentages in Solidity
We canβt do floating point maths in Solidity. But calculating percentages does not require floating point math.
A quick example is shown below, based on https://ethereum.stackexchange.com/questions/52781/division-percentages-in-solidity-a-workaround
function getPercent(uint part, uint whole) public pure returns(uint percent) {
uint numerator = part * 1000;
require(numerator > part); // overflow. Should use SafeMath throughout if this was a real implementation especially on older versions of Solidity
uint temp = numerator / whole + 5; // proper rounding up
return temp / 10;
}
Also see my page on floating point math in Solidty
This post is incomplete and a work-in-progress
I'll update it soon and flesh it out with
more
info!
Spotted a typo or have a suggestion to make this crypto dev article better? Please let me know!
Previous post
π Solidity Auditing online quiz
Learn how to audit smart contracts by looking at some example code and trying to find the bugs
β½ Solidity Gas Optimizations Guide
How to optimize and reduce gas usage in your smart contracts in Solidity
π§ͺ Guide to testing with Foundry
Guide to adding testing for your Solidity contracts, using the Foundry and Forge tools
π Guide to UTXO
UTXO and the UTXO set (used by blockchains such as Bitcoin) explained
π Solidity Assembly Guide
Introduction guide to using assembly in your Solidity smart contracts
π¦ Ethereum EOF format explained
Information explaining what the upcoming Ethereum EOF format is all about