How to calculate percentage?

Asked

Viewed 22,962 times

6

I have a variable that dynamically receives from the database, a floating number that is the percentage to be taken out of a certain value. How do I take this percentage away from a value?

For example:

$total = 4000;
$pctm = 30.00;
$valor_descontado = $total-$pctm.'%';

But that way, it doesn’t work.

6 answers

18


  • Resolved, thanks not only to you, but to all.

  • @Maniero, how do I get the percentage of the subtraction result of 2500000 by 1950000. I tried with the proposal ai, but it does not work, it does not return the value of the percentage. Is it because the number is large? It has how to do this?

  • @Maniero I want to know what is the percentage of the number I subtract. For example. My product costs 100 real, I will give a discount of 25 real, IE decrease... is a simple account we already know head to head that the percentage of 100 real minus 25 is 25%. But what for larger numbers? For example, what is the percentage of 5 million - minus 1 million seven hundred and fifty thousand and 80 reais? I am searching for "%%% "of the result of the number I just subtracted...

8

Just make a simple calculation.

$valor_descontado = $total - $total * $pctm / 100.0;

whereas:

30% = 30/100

8

Just use rules of 3:

function porcentagem_nx ( $parcial, $total ) {
    return ( $parcial * 100 ) / $total;
}

With this function will facilitate the percentage calculation, to use enough:

 porcentagem_nx(20, 100); // 20

View working on Codepag

2

You can also do as follows:

$total = 4000
$pctm = 30.00

$valor_com_desconto = $total - ($total * $pctm * 0.01)

Divide by 100 and multiply by 0.01 gives the same result.

2

I usually do so to capture the result of a discount:

$total = 4000;
$pctm = 30.00;
$valor_com_desconto = $total - (($total * $pctm) / 100);
echo $valor_com_desconto;

Obs: mathematics always executes multiplication after division. In this example the logic is separated.

  • In fact, multiplication and division have the same "importance" in the order of execution, the famous P/E/MD/AS http://pt.wikihow.com/Calcular-uma-Express%C3%A3o-Usando-PEMDAS

2

Another way is by the multiplication factor, example:

If a product increased by 30% then its multiplication factor is 1 + increment rate, this rate being 0.3. Therefore, its multiplication factor is 1.3.

If a product had a 30% discount then its multiplication factor is 1 - decrease rate, this rate being 0.3. Therefore, its multiplication factor is 0.7.

$total = 4000;
$pctm = -30.00;//desconto de 30%
echo "Com desconto: " . $total * (1+($pctm/100));
echo PHP_EOL;
$pctm = 30.00;//acréscimo de 30%
echo "Com acréscimo: " . $total * (1+($pctm/100));

IDEONE

Browser other questions tagged

You are not signed in. Login or sign up in order to post.