how to calculate percentage in solidity
Asked Answered
S

1

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?

Soffit answered 9/7, 2021 at 1:54 Comment(0)
A
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`
Addax answered 9/7, 2021 at 7:46 Comment(4)
Would then "a1.transfer(amount.div(100).mul(80));" be the same thing?Royalty
@Alessandro Yes for amounts 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.Addax
what if you want a decimal percentage value? Example 0,001%Libreville
@Libreville 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)Addax

© 2022 - 2024 — McMap. All rights reserved.