9
    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?

Spacebar
  • 95
  • 1
  • 1
  • 3

1 Answers1

15

80% is the same thing as

  • multiply by 80, and then divide by 100

    as well as

  • multiply by 4, and then divide by 5

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

You can simplify the 20% in the same way:

  • multiply by 20 and then divide by 100

    which is

  • multiply by 1, and then divide by 5

    which is simply

  • divide by 5

a2.transfer(amount.div(5)); // 20% of `amount`
BonisTech
  • 342
  • 3
  • 15
Petr Hejda
  • 40,554
  • 8
  • 72
  • 100
  • Would then "a1.transfer(amount.div(100).mul(80));" be the same thing? –  Nov 24 '21 at 13:33
  • 2
    @Alessandro Yes for `amount`s divisible by 100... If you had `amount` value 50, the `.div(5).mul(4)` would return 40 as expected. But the `.div(100).mul(80)` would return 0, because at first it calculates `50 / 100` (which results in the unsigned integer 0), and then `0 * 80`. – Petr Hejda Nov 24 '21 at 13:47
  • what if you want a decimal percentage value? Example 0,001% – R01010010 May 16 '22 at 12:45
  • @R01010010 Then you can divide by a larger number. As per your example, if you want to get 0.001% of `amount`, then you calculate `amount.div(100000)` – Petr Hejda May 16 '22 at 16:05