PHP Calculate Percentage
In this article, you will learn how to calculate the percentage of a number using the PHP programming language. Such a type of logical query can be asked in a programming interview or need to be implemented during some application development. In some cases, when there is a need to find the ratio or portion of a quantity as a part of another quantity, you should communicate it as a percentage. This exercise will basically simplify the essential function that we will use to have the option to calculate a percentage.
In this exercise, let's assume that we have two variables: one is the number you wish to change into a percentage, and the other is the total. Calculating percentage means finding the share of a whole in terms of 100. Here, we have defined a new function, cal_percentage(), and taken two variables, $num_amount and $num_total. Within this function, we have applied the mathematical formula of percentage calculation, i.e., we divide the amount by the total amount and multiply the result by 100, so that we can get a percentage. In the next line, we have used the number_format() function that formats a number with grouped thousands.
PHP program to Calculate Percentage
<?php
// defining function
function cal_percentage($num_amount, $num_total) {
$count1 = $num_amount / $num_total;
$count2 = $count1 * 100;
$count = number_format($count2, 0);
return $count;
}
// calling function to calculate percentage
echo "Percentage of 39 in 100 : ".cal_percentage(39, 100).'%<br/>';
echo "Percentage of 26 in 200 : ".cal_percentage(26, 200).'%<br/>';
echo "Percentage of 17 in 150 : ".cal_percentage(17, 150).'%<br/>';
echo "Percentage of 30 in 400 : ".cal_percentage(30, 400).'%<br/>';
echo "Percentage of 11 in 190 : ".cal_percentage(11, 190).'%<br/>';
?>
Output of the above code-
Percentage of 39 in 100 : 39%
Percentage of 26 in 200 : 13%
Percentage of 17 in 150 : 11%
Percentage of 30 in 400 : 8%
Percentage of 11 in 190 : 6%
Related Articles
Age calculator in PHPPHP capitalize first letter
PHP set timezone
Remove duplicates from array PHP
Electricity bill program in PHP
PHP String Contains
PHP reverse a string without predefined function
PHP random quote generator
PHP substr() function
PHP convert string into an array
PHP remove HTML and PHP tags from string
Import Excel File into MySQL using PHP
How to display PDF file in PHP from database
How to read CSV file in PHP and store in MySQL
Create And Download Word Document in PHP
PHP SplFileObject Standard Library
Simple File Upload Script in PHP
Sending form data to an email using PHP
Recover forgot password using PHP and MySQL
Php file based authentication
Simple PHP File Cache
How to get current directory, filename and code line number in PHP