How to divide two numbers and get the percentage in PHP

PHPz
Release: 2023-04-03 14:58:02
Original
1148 people have browsed it

In PHP, you can use the following method to get the percentage of two numbers.

First, we need to clarify the values ​​​​of the two numbers, and we can use variables to store these values.

$numerator = 20;  // 分子
$denominator = 100;  // 分母
Copy after login

Next, we can calculate the percentage using the following code:

$percentage = ($numerator / $denominator) * 100;
Copy after login

In this example, first we divide the numerator by the denominator and then multiply the result by 100. This calculates the percentage of two numbers.

Finally, we can convert the result to a string and output:

echo "分子为 $numerator,分母为 $denominator,百分比为 " . round($percentage, 2) . "%。";
Copy after login

In this example, we use the round() function to round the result to two decimal places Bit. You can change it yourself as needed.

The following is a complete sample code:

$numerator = 20;  // 分子
$denominator = 100;  // 分母

$percentage = ($numerator / $denominator) * 100;

echo "分子为 $numerator,分母为 $denominator,百分比为 " . round($percentage, 2) . "%。";
Copy after login

Run this code, you will get the following output:

分子为 20,分母为 100,百分比为 20%。
Copy after login

Of course, you can also encapsulate variables and calculation processes into function for easy reuse later. For example:

function getPercentage($numerator, $denominator) {
    $percentage = ($numerator / $denominator) * 100;
    return round($percentage, 2);
}

$numerator = 20;  // 分子
$denominator = 100;  // 分母

echo "分子为 $numerator,分母为 $denominator,百分比为 " . getPercentage($numerator, $denominator) . "%。";
Copy after login

In this way, you only need to call this function every time you calculate the percentage.

In short, it is very simple to calculate the percentage between two numbers using PHP. Remember to encapsulate it into a function as needed to facilitate future use.

The above is the detailed content of How to divide two numbers and get the percentage in PHP. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template