New to blockchain software development? Read my beginners guide here

How to calculate percentages in Solidity

Created on August 2022 β€’ Tags: solidityguides

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!

See all posts (70+ more)

See all posts (70+ more)

Was this post helpful? πŸ“§

If you liked this content and want to receive emails about future posts like this, enter your email. I'll never spam you.

Or follow me on @CryptoGuide_Dev on twitter

By using this site, you agree that you have read and understand its Privacy Policy and Terms of Use.
Use any information on this site at your own risk, I take no responsibility for the accuracy of safety of the information on this site.