Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP calculate percentages

Tags:

php

percentage

I need some help. It's a simple code, but I don't have idea how to write in down. I have the numbers:

$NumberOne = 500;
$NumberTwo = 430;
$NumberThree = 150;
$NumberFour = 30; 

At all this is:

$Everything = 1110; // all added

Now I want to show what percentage is for example $NumberFour of everything or what percentage is $NumberTwo of $Everything. So the "market share".

like image 658
Chris Avatar asked Nov 27 '22 09:11

Chris


1 Answers

Use some simple maths: divide the number you wish to find the percentage for by the total and multiply by 100.

Example:

$total = 250;
$portion = 50;
$percentage = ($portion / $total) * 100; // 20

Solution to original example

To get $NumberFour as a percentage of the total amount you'd use:

$percentage = ($NumberFour / $Everything) * 100;

Rounding

Depending on the numbers you're working with, you may want to round the resulting percentage. In my initial example, we get 20% which is a nice round number. The original question however uses 1110 as the total and 30 as the number to calculate the percentage for (2.70270...).

PHP's built in round() function could be useful when working with percentages for display: https://www.php.net/manual/en/function.round.php

echo round($percentage, 2) . '%'; // 2.7% -- (30 / 1110) * 100 rounded to 2dp

Helper Functions

I would only contemplate creating helper functions when their use justifies it (if calculating and displaying a percentage isn't a one-off). I've attached an example below tying together everything from above.

function format_percentage($percentage, $precision = 2) {
    return round($percentage, $precision) . '%';
}

function calculate_percentage($number, $total) {

    // Can't divide by zero so let's catch that early.
    if ($total == 0) {
        return 0;
    }

    return ($number / $total) * 100;
}

function calculate_percentage_for_display($number, $total) {
    return format_percentage(calculate_percentage($number, $total));
}

echo calculate_percentage_for_display(50, 250); // 20%
echo calculate_percentage_for_display(30, 1110); // 2.7%
echo calculate_percentage_for_display(75, 190); // 39.47%
like image 165
Nathan Dawson Avatar answered Dec 05 '22 17:12

Nathan Dawson