How to calculate percentage?

4

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

For example:

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

But that does not work.

    
asked by anonymous 21.09.2015 / 21:51

6 answers

13

This is basic math. To calculate a percentage, divide by 100 and multiply by the percentage you want.

$total = 4000;
$pctm = 30.00;
$valor_descontado = $total - ($total / 100 * $pctm); //os parenteses são desnecessários

See running on ideone .

Of course we are talking about monetary values and there you have another problem .

    
21.09.2015 / 21:53
7

Just do a simple calculation.

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

Considering that:

  

30% = 30/100

    
21.09.2015 / 21:54
5

Just use 3:

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

With this function it will facilitate the calculation of percentage, to use it suffices:

 porcentagem_nx(20, 100); // 20

Seeing working on Codepag

    
21.09.2015 / 21:56
2

I usually do this 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 performs multiplication after division. In this example the logic is separated.

    
21.09.2015 / 22:13
2

You can also do this as follows:

$total = 4000
$pctm = 30.00

$valor_com_desconto = $total - ($pctm * 0.01)
    
17.12.2015 / 15:59
2

Another way is by multiplication factor, for example:

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

If a product has a discount of 30% then its multiplication factor is 1 - rate of decrease, 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

    
22.12.2016 / 13:26