Solidity Design Patterns: Multiply before Dividing

Do your multiplication before division!

This one is actually even true in JavaScript. To see why this is important, open up your browser console and type

console.log((30 * 100 * 13) / 13)
< 3000
console.log((30 / 13) * 100 * 13)
< 2999.9999999999995

Not always sufficient!

Sometimes this is not good enough. If we are computing pay-outs for Ether, then it is most probably fine. After all, who cares about missing out on a single Wei in payment? As long as the computations are consistent and you’re not relying on all payout summing up to exactly the same amount of Wei as expected, you are fine.

uint256 numerator = 30 * 100 * 13;
uint256 denominator = 13;

--

--

Lead smart contract developer at InjectiveProtocol. Passionate about the revolution in finances. And sport. And healthy food.

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Markus Waas — soliditydeveloper.com

Markus Waas — soliditydeveloper.com

Lead smart contract developer at InjectiveProtocol. Passionate about the revolution in finances. And sport. And healthy food.