how to calculate percentage in solidity

Viewed 8319
    function splitAmount(uint256 amount) private {
        a1.transfer(amount.div(2));
        a2.transfer(amount.div(2));
    }

I've seen other threads on this but I feel like over complicate things. With this code the amount is evenly split between a1 and a2 with division by 2.

How would one do something like a 80/20 split with the same code?

1 Answers

80% is the same thing as

  • divide by 100, and then multiply by 80

    as well as

  • divide by 5, and then multiply by 4

a1.transfer(amount.div(5).mul(4)); // 80% of `amount`

You can simplify the 20% in the same way:

  • divide by 100 and then multiply by 20

    which is

  • divide by 5, and then multiply by 1

    which is simply

  • divide by 5

a2.transfer(amount.div(5)); // 20% of `amount`
Related